import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ModalDialogService, RouterExtensions } from '@nativescript/angular';
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 { MeetingDateDetailResponse } from '../../entities/output/meetingDateDetailResponse';
import { OccupationAllUnitResult } from '../../entities/output/occupationAllUnitResult';
import { RealtyAllResult } from '../../entities/output/realtyAllResult';
import { WeekDays } from '../../entities/weekDays';
import {
    LoadMeetingDateDetail,
    LoadOccupationAllUnit,
    LoadRealtyAll,
    UpdateMeetingDate
} 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-update.component.html',
    styleUrls: ['./_meeting-date-update.component.scss']
})

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

    id: number;
    availablePlaces: MeetingPlace[] = [ new MeetingPlace(undefined, 'Žádná') ];

    meeting: MeetingDateDetailResponse = new MeetingDateDetailResponse();

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

    ngOnInit(): void {
        this.id = +this.route.snapshot.params['id'];
        this.store.dispatch(new LoadMeetingDateDetail(this.id))
            .pipe(withLatestFrom(this.meetingDateDetail$))
            .subscribe(([_, output]) => {
                this.meeting = output;
                if (this.meeting.ID_Occupation === null) {
                    this.meeting.ID_Occupation = undefined;
                    this.meeting.Occupation = 'Žádná';
                }
            }, 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 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() {
        const options = {
            message: 'Zvolte den',
            cancelButtonText: 'Zrušit',
            actions: WeekDays.weekDays.map(obj => obj.day)
        };

        action(options).then((result) => {
            const day = WeekDays.weekDays.find(obj => obj.day === result);
            this.meeting.ID_WeekDay = day.id;
            this.meeting.WeekDay = day.day;
        });
    }

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

        action(options).then((result) => {
            const place = this.availablePlaces.find(obj => obj.displayName === result);
            this.meeting.ID_Occupation = place.occupationId;
            this.meeting.Occupation = place.displayName;
        });
    }

    showTimeFromModal() {
        const timeFrom = DurationConverter.fromDuration(this.meeting.TimeFrom);
        const options = {
            viewContainerRef: this.viewContainerRef,
            context: { hours: timeFrom.hours, minutes: timeFrom.minutes },
            fullscreen: false
        };
        this.modalService.showModal(ModalTimePickerComponent, options)
            .then((result) => {
                if (result) {
                    this.meeting.TimeFrom = DurationConverter.toDuration(result);
                }
            });
    }

    showTimeToModal() {
        const timeTo = DurationConverter.fromDuration(this.meeting.TimeTo);
        const options = {
            viewContainerRef: this.viewContainerRef,
            context: { hours: timeTo.hours, minutes: timeTo.minutes },
            fullscreen: false
        };
        this.modalService.showModal(ModalTimePickerComponent, options)
            .then((result) => {
                if (result) {
                    this.meeting.TimeTo = DurationConverter.toDuration(result);
                }
            });
    }

    onSaveTap() {
        if (this.meeting.Periodicity === '') {
            feedbackMessage(FeedbackType.Error, 'Úprava schůzky', `Vyplňte všechny údaje.`);

            return;
        }

        const timeFrom = DurationConverter.fromDuration(this.meeting.TimeFrom);
        const timeTo = DurationConverter.fromDuration(this.meeting.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 UpdateMeetingDate(
            this.id,
            this.meeting.ID_WeekDay,
            this.meeting.WeekDay,
            this.meeting.TimeFrom,
            this.meeting.TimeTo,
            this.meeting.Periodicity,
            this.meeting.ID_Occupation))
            .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);
    }
}
