import { Component, ElementRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ModalDialogService, RouterExtensions } from '@nativescript/angular';
import { EventData, TextField } from '@nativescript/core';
import { action } from '@nativescript/core/ui/dialogs';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { feedbackMessage } from '~/pages/material/utils/feedback-messages';
import { ModalTimePickerComponent } from '../../components/modal-view-time-picker/modal-view-time-picker.component';
import { MeetingPlace } from '../../entities/meetingPlace';
import { OccupationAllUnitResult } from '../../entities/output/occupationAllUnitResult';
import { RealtyAllResult } from '../../entities/output/realtyAllResult';
import { WeekDays } from '../../entities/weekDays';
import { InsertMeetingDate, LoadOccupationAllUnit, LoadRealtyAll } from '../../state-mgmt/meeting-date.actions';
import { MeetingDateState } from '../../state-mgmt/meeting-date.state';
import { DurationConverter } from '../../utils/durationConverter';

@Component({
    selector: 'MeetingDateNew',
    moduleId: module.id,
    templateUrl: './meeting-date-new.component.html',
    styleUrls: ['./_meeting-date-new.component.scss']
})

export class MeetingDateNewComponent implements OnInit {
    @Select(MeetingDateState.getOccupationAllUnit) occupationAllUnit$: Observable<OccupationAllUnitResult[]>;
    @Select(MeetingDateState.getRealtyAll) realtyAll$: Observable<RealtyAllResult[]>;
    @Select(MeetingDateState.isLoading) isLoading$: Observable<boolean>;

    weekDay: { day, id } = null;
    timeFrom: string = null;
    timeTo: string = null;
    availablePlaces: MeetingPlace[] = [ new MeetingPlace(undefined, 'Žádná') ];
    selectedPlace: MeetingPlace = null;

    @ViewChild('periodicity', {static: false}) periodicity: ElementRef;

    constructor(
        private store: Store,
        private routerExtensions: RouterExtensions,
        private route: ActivatedRoute,
        private viewContainerRef: ViewContainerRef,
        private modalService: ModalDialogService
     ) {}

    ngOnInit(): void {
        this.store.dispatch(new LoadOccupationAllUnit())
            .pipe(withLatestFrom(this.occupationAllUnit$))
            .subscribe(([_, occupationAllOutput]) => {
                this.store.dispatch(new LoadRealtyAll())
                    .pipe(withLatestFrom(this.realtyAll$))
                    .subscribe(([_, realtyAllOutput]) => {
                        occupationAllOutput.forEach(occupation => {
                            const desiredRealtyName = realtyAllOutput.find(realty => realty.ID === occupation.ID_Realty).DisplayName;
                            this.availablePlaces.push(new MeetingPlace(occupation.ID, desiredRealtyName + ' - ' + occupation.RealtyType));
                        });
                    }, 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();
                    });
            }, 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();
            });
    }

    onTapWeekDaySelect(args: EventData) {
        const options = {
            message: 'Zvolte den',
            cancelButtonText: 'Zrušit',
            actions: WeekDays.weekDays.map(obj => obj.day)
        };

        action(options).then((result) => {
            this.weekDay = WeekDays.weekDays.find(obj => obj.day === result);
            (<TextField>args.object).text = this.weekDay.day;
        });
    }

    onTapMeetingPlaceSelect(args: EventData) {
        const options = {
            message: 'Zvolte klubovnu',
            cancelButtonText: 'Zrušit',
            actions: this.availablePlaces.map(obj => obj.displayName)
        };

        action(options).then((result) => {
            this.selectedPlace = this.availablePlaces.find(obj => obj.displayName === result);
            (<TextField>args.object).text = this.selectedPlace.displayName;
        });
    }

    showTimeFromModal(args: EventData) {
        const txtField = <TextField>args.object;
        const options = {
            viewContainerRef: this.viewContainerRef,
            context: { hours: 0, minutes: 0 },
            fullscreen: false
        };
        this.modalService.showModal(ModalTimePickerComponent, options)
            .then((result) => {
                if (result) {
                    this.timeFrom = DurationConverter.toDuration(result);
                    txtField.text = DurationConverter.fromDurationToString(this.timeFrom);
                }
            });
    }

    showTimeToModal(args: EventData) {
        const txtField = <TextField>args.object;
        const options = {
            viewContainerRef: this.viewContainerRef,
            context: { hours: 0, minutes: 0 },
            fullscreen: false
        };
        this.modalService.showModal(ModalTimePickerComponent, options)
            .then((result) => {
                if (result) {
                    this.timeTo = DurationConverter.toDuration(result);
                    txtField.text = DurationConverter.fromDurationToString(this.timeTo);
                }
            });
    }

    onSaveTap() {
        if (this.weekDay === null ||
            this.timeFrom === null ||
            this.timeTo === null ||
            this.periodicity.nativeElement.text === '' ||
            this.selectedPlace === null) {
            feedbackMessage(FeedbackType.Error, 'Přidání schůzky', `Vyplňte všechny údaje.`);

            return;
            }

        const timeFrom = DurationConverter.fromDuration(this.timeFrom);
        const timeTo = DurationConverter.fromDuration(this.timeTo);
        if ((timeTo.hours < timeFrom.hours) || (timeTo.hours === timeFrom.hours && timeTo.minutes <= timeFrom.minutes)) {
            feedbackMessage(FeedbackType.Error, 'Úprava schůzky', `Čas do nemůže být menší než čas od.`);

            return;
        }

        this.store.dispatch(new InsertMeetingDate(
            this.weekDay.id,
            this.weekDay.day,
            this.timeFrom,
            this.timeTo,
            this.periodicity.nativeElement.text,
            this.selectedPlace.occupationId))
            .subscribe(() => {
                feedbackMessage(FeedbackType.Success, 'Ukládání schůzky', 'Schůzka byla úspěšně uložena');
                this.routerExtensions.back();
            }, err => {
                console.log(err);
                feedbackMessage(FeedbackType.Error, 'Ukládání schůzky', `Při ukládání schůzky došlo k chybě. Zkontrolujte prosím vaše internetové připojení.`);
            });
    }

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

    get saveIcon() {
        return String.fromCharCode(0xf0c7);
    }
}
