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 { action } from '@nativescript/core/ui/dialogs';
import { Actions, ofActionSuccessful, 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 { WarehouseItemReservationAllOutput } from '../../entities/output/warehouseItemReservationAllOutput';
import { CreateWarehouseItemRentInsert, LoadWarehouseItemReservationAll } from '../../state-mgmt/material-lend.action';
import { MaterialLendState } from '../../state-mgmt/material-lend.state';
import { feedbackMessage } from '../../utils/feedback-messages';
import { czechStringfromDate, dateFromCzechString } from '../../utils/myFunctions';

@Component({
    selector: 'MaterialLend',
    moduleId: module.id,
    templateUrl: './material-lend.component.html',
    styleUrls: ['./material-lend.component.scss']
})

export class MaterialLendComponent implements OnInit {
    @ViewChild('reservationsField', {static: true}) reservationsField: ElementRef;
    @ViewChild('rentDate', {static: true}) rentDate: ElementRef;
    @ViewChild('note', {static: true}) note: ElementRef;

    @Select(MaterialLendState.getWarehouseItemReservationAll) warehouseItemReservationAll$: Observable<WarehouseItemReservationAllOutput[]>;
    @Select(MaterialLendState.isLoading) isLoading$: Observable<boolean>;

    idItem: number;
    nameItem: string;
    reservations: WarehouseItemReservationAllOutput[];
    othersIsLoading: boolean;

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

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.idItem = +JSON.parse(this.route.snapshot.params['id']);
        this.nameItem = this.route.snapshot.params['name'];
        this.store.dispatch(new LoadWarehouseItemReservationAll(+this.route.snapshot.params['id'], true))
        .pipe(withLatestFrom(this.warehouseItemReservationAll$))
        .subscribe(([_, reservations]) => {

            this.reservations = reservations.sort((a, b) => a.ID - b.ID);
            for (let i = 0; i < this.reservations.length; i++) {
                this.reservations[i].idForDisplay = i + 1;
            }
            this.reservationsField.nativeElement.text = this.reservations.length >= 1 ? this.reservations[0].toString() : '';
        }, err => {
            feedbackMessage(FeedbackType.Error, 'Načtení rezervací', 'Nepodařilo se načíst detaily rezervace.');
        });
        this.rentDate.nativeElement.text = czechStringfromDate(new Date());

        this.actions$.pipe(ofActionSuccessful(CreateWarehouseItemRentInsert)).subscribe(() => {
            feedbackMessage(FeedbackType.Success, 'Rezervace', `Rezervace položky ${this.nameItem} byla potvrzena.`);
            this.routerExtensions.back();
        });
    }

    onTapReservationSelect(args: EventData) {
        const options = {
            message: 'Zvolte rezervaci',
            cancelButtonText: 'Zrušit',
            actions: this.reservations.map(obj => obj.toString())
        };

        action(options).then(async (result) => {
            (<TextField>args.object).text = this.reservations.find(obj => obj.toString() === result).toString();
        });
    }

    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);
                }
            });
        }

    lendItem() {
        const reservation = this.reservations.find(obj => obj.toString() === this.reservationsField.nativeElement.text);
        const startDate = dateFromCzechString(this.rentDate.nativeElement.text);
        this.store.dispatch(new CreateWarehouseItemRentInsert(this.idItem, reservation.ID, startDate ? startDate.toISOString() : null, this.note.nativeElement.text));

    }

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

    get lendIcon() {
        return String.fromCharCode(0xf360);
    }
}
