import { Component, ElementRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { ModalDialogOptions, ModalDialogService, RouterExtensions } from '@nativescript/angular';
import { EventData, TextField } from '@nativescript/core';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { ModalDatePickerComponent } from '../../components/modal-view-date-picker/modal-view-date-picker.component';
import { WarehouseAllOutput } from '../../entities/output/warehouseAllOutput';
import { WarehouseItemReservationDetailOutput } from '../../entities/output/warehouseItemReservationDetailOutput';
import { WarehouseItemReservationUpdateOutput } from '../../entities/output/warehouseItemReservationUpdateOutput';
import { CreateReservationUpdate, LoadReservationDetail } from '../../state-mgmt/reservation-update.action';
import { ReservationUpdateState } from '../../state-mgmt/reservation-update.state';
import { feedbackMessage } from '../../utils/feedback-messages';
import { czechStringfromDate, dateFromCzechString } from '../../utils/myFunctions';

@Component({
    selector: 'ReservationUpdate',
    moduleId: module.id,
    templateUrl: './reservation-update.component.html',
    styleUrls: ['./reservation-update.component.scss']
})

export class ReservationUpdateComponent implements OnInit {
    @Select(ReservationUpdateState.getReservationDetail) reservationDetail$: Observable<WarehouseItemReservationDetailOutput>;
    @Select(ReservationUpdateState.getReservationUpdate) reservationUpdate$: Observable<WarehouseItemReservationUpdateOutput>;
    @Select(ReservationUpdateState.isLoading) isLoading$: Observable<boolean>;

    @ViewChild('person', {static: true}) person: ElementRef;
    @ViewChild('personTelephone', {static: true}) personTelephone: ElementRef;
    @ViewChild('personEmail', {static: true}) personEmail: ElementRef;
    @ViewChild('dateTo', {static: true}) dateTo: ElementRef;

    reservationDetail: WarehouseItemReservationDetailOutput;
    warehouses: WarehouseAllOutput[];
    othersIsLoading: boolean;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private modalService: ModalDialogService,
        private viewContainerRef: ViewContainerRef
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (RegExp('\/material\/reservationUpdate\/[0-9]+').test(this.router.url)) {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadReservationDetail(this.route.snapshot.params['id']))
            .pipe(withLatestFrom(this.reservationDetail$))
            .subscribe(([_, detail]) => {
                this.reservationDetail = detail;
                this.fillTextFields(this.reservationDetail);
            }, err => {
                feedbackMessage(FeedbackType.Error, 'Načtení skladů', 'Nepodařilo se načíst sklady.');
                console.log(err);
            });
    }

    fillTextFields(reservation: WarehouseItemReservationDetailOutput) {
        this.othersIsLoading = true;
        this.person.nativeElement.text = reservation.Person;
        this.personTelephone.nativeElement.text = reservation.Phone;
        this.personEmail.nativeElement.text = reservation.Email;
        this.dateTo.nativeElement.text = reservation.EstimatedEndDate ? czechStringfromDate(new Date(reservation.EstimatedEndDate)) : '';
        this.othersIsLoading = false;
    }

    showDate(args: EventData) {
        this.othersIsLoading = true;
        const txtField = <TextField>args.object;
        const date = txtField.text.split('.');
        const options: ModalDialogOptions = {
            viewContainerRef: this.viewContainerRef,
            context: {
                day: date.length === 3 ? date[0].trim() : new Date().getDate(),
                month: date.length === 3 ? date[1].trim() : new Date().getMonth() + 1,
                year: date.length === 3 ? date[2].trim() : new Date().getFullYear(),
                minDate: null
            },
            fullscreen: false
        };
        this.othersIsLoading = false;
        this.modalService.showModal(ModalDatePickerComponent, options)
            .then((result: Date) => {
                if (result) {
                    txtField.text = czechStringfromDate(result);
                }
            });
    }

    updateReservation() {
        if (this.person.nativeElement.text === '') {
            feedbackMessage(FeedbackType.Error, 'Úprava rezervace', `Vyplňte kontaktní osobu.`);
        } else if (this.personEmail.nativeElement.text !== '' && !RegExp('^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$').test(this.personEmail.nativeElement.text)) {
            feedbackMessage(FeedbackType.Error, 'Úprava rezervace', `Email není ve správném formátu.`);
        } else {
            const dateTo = dateFromCzechString(this.dateTo.nativeElement.text);
            this.store.dispatch(new CreateReservationUpdate(
                this.reservationDetail.ID, this.reservationDetail.ID_Warehouse,
                this.person.nativeElement.text, this.personTelephone.nativeElement.text,
                this.personEmail.nativeElement.text, (dateTo ? dateTo.toISOString() : undefined)))
                .pipe(withLatestFrom(this.reservationUpdate$))
                .subscribe(([_, result]) => {
                    feedbackMessage(FeedbackType.Success, 'Úprava rezervace', `Rezervace byla úspěšně upravena.`);
                    this.routerExtensions.back();
                }, err => {
                    console.log(err);
                    feedbackMessage(FeedbackType.Error, 'Úprava rezervace', `Při úpravě rezervace došlo k chybě. Zkontrolujte prosím zadané hodnoty.`);
                });
        }
    }

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

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