import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ModalDialogOptions, ModalDialogService, RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { UserRoleAllOutput } from '~/core/entities/output/userRoleAllOutput';
import { AppState } from '~/core/state-mgmt/app.state';
import { feedbackMessage } from '~/pages/material/utils/feedback-messages';
import { ModalViewEditnoteComponent } from '../../components/modal-view-editnote/modal-view-editnote.component';
import { AdvertisingCategoryAllResult } from '../../entities/output/advertisingCategoryAllResult';
import { AdvertisingDetailResult } from '../../entities/output/advertisingDetailResult';
import { MeetingDateAllResult } from '../../entities/output/meetingDateAllResult';
import {
    LoadAdvertisingCategoryAll,
    LoadAdvertisingDetail,
    LoadMeetingDateAll,
    UpdateAdvertisingDetail
} from '../../state-mgmt/advertising.actions';
import { AdvertisingState } from '../../state-mgmt/advertising.state';

@Component({
    selector: 'Advertising',
    moduleId: module.id,
    templateUrl: './advertising.component.html',
    styleUrls: ['./_advertising.component.scss']
})

export class AdvertisingComponent implements OnInit {
    @Select(AdvertisingState.getAdvertisingDetail) advertisingDetail$: Observable<AdvertisingDetailResult>;
    @Select(AdvertisingState.getMeetingDateAll) meetingDateAll$: Observable<MeetingDateAllResult[]>;
    @Select(AdvertisingState.getAdvertisingCategoryAll) advertisingCategoryAll$: Observable<AdvertisingCategoryAllResult[]>;
    @Select(AppState.getUserRoleAll) userRoleAll$: Observable<UserRoleAllOutput[]>;
    @Select(AdvertisingState.isLoading) isLoading$: Observable<boolean>;

    advertisingDetail: AdvertisingDetailResult;
    meetingDateAll: MeetingDateAllResult[];
    advertisingCategoryAll: AdvertisingCategoryAllResult[];
    showMeetings: boolean;
    showCategories: boolean;

    canEdit: boolean = false;

    constructor(
        private store: Store,
        private routerExtensions: RouterExtensions,
        private viewContainerRef: ViewContainerRef,
        private modalService: ModalDialogService,
        private route: ActivatedRoute) {
            this.showMeetings = true;
            this.showCategories = true;
     }

    onLoad() {
        this.store.dispatch(new LoadAdvertisingDetail())
            .pipe(withLatestFrom(this.advertisingDetail$))
            .subscribe(([_, result]) => {
                this.advertisingDetail = result;
            }, err => {
                console.log(err);
                feedbackMessage(FeedbackType.Error, 'Načítání dat', `Při načítání dat došlo k chybě. Zkontrolujte prosím vaše internetové připojení.`);
                this.routerExtensions.back();
            });

        this.store.dispatch(new LoadMeetingDateAll())
            .pipe(withLatestFrom(this.meetingDateAll$))
            .subscribe(([_, result]) => {
                this.meetingDateAll = result;
            }, err => {
                console.log(err);
                feedbackMessage(FeedbackType.Error, 'Načítání dat', `Při načítání dat došlo k chybě. Zkontrolujte prosím vaše internetové připojení.`);
                this.routerExtensions.back();
            });
        this.store.dispatch(new LoadAdvertisingCategoryAll())
            .pipe(withLatestFrom(this.advertisingCategoryAll$))
            .subscribe(([_, result]) => {
                this.advertisingCategoryAll = result;
            }, err => {
                console.log(err);
                feedbackMessage(FeedbackType.Error, 'Načítání dat', `Při načítání dat došlo k chybě. Zkontrolujte prosím vaše internetové připojení.`);
                this.routerExtensions.back();
            });
    }

    ngOnInit(): void {
        this.canEdit = this.route.snapshot.params['permission'];
    }

    onNoteEdit() {
        this.showModalEditNote().then(newNote => {
            if (newNote && newNote !== this.advertisingDetail.Note) {
                this.store.dispatch(new UpdateAdvertisingDetail(newNote))
                    .subscribe(() => {
                        feedbackMessage(FeedbackType.Success, 'Ukládání poznámky', 'Poznámka byla úspěšně uložena');
                        this.advertisingDetail.Note = newNote;
                    }, err => {
                        console.log(err);
                        feedbackMessage(FeedbackType.Error, 'Ukládání poznámky', `Při ukládání poznámky došlo k chybě. Zkontrolujte prosím vaše internetové připojení.`);
                        this.routerExtensions.back();
                    });
            }
        });
    }

    onMeetingTap(id: number) {
        this.routerExtensions.navigate(['advertising/meetingDetail', id, this.canEdit], {transition: transitionOptions});
    }

    onCategoryTap(id: number) {
        this.routerExtensions.navigate(['advertising/advertisingCategoryDetail', id, this.canEdit], {transition: transitionOptions});
    }

    onNavTap(path: string) {
        setTimeout(() => {
            this.routerExtensions.navigate([path, this.canEdit], {transition: transitionOptions});
        }, 10);
    }

    onMeetingsExpandTap() {
        this.showMeetings = !this.showMeetings;
    }

    onCategoriesExpandTap() {
        this.showCategories = !this.showCategories;
    }

    onBackButton(): void {
        this.routerExtensions.back();
    }

    private showModalEditNote() {
        const options: ModalDialogOptions = {
            viewContainerRef: this.viewContainerRef,
            context: {
                note: this.advertisingDetail.Note
            },
            fullscreen: false
        };

        return this.modalService.showModal(ModalViewEditnoteComponent, options);
    }

    get editIcon() {
        return String.fromCharCode(0xf304);
    }

    get newIcon() {
        return String.fromCharCode(0xf067);
    }

    get downIcon() {
        return String.fromCharCode(0xf107);
    }

    get rightIcon() {
        return String.fromCharCode(0xf105);
    }
}
