import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { ModalDialogOptions, 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 { transitionOptions } from '~/constants/shared.constants';
import { ModalHelpComponent } from '../../components/modal-view-help/modal-view-help.component';
import { WarehouseAllOutput } from '../../entities/output/warehouseAllOutput';
import { WarehouseItemAllLentOutput } from '../../entities/output/warehouseItemAllLentOutput';
import { LoadWarehouseAll, LoadWarehouseItemAllLent } from '../../state-mgmt/reservation-lent.action';
import { ReservationLentState } from '../../state-mgmt/reservation-lent.state';
import { feedbackMessage } from '../../utils/feedback-messages';

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

export class ReservationLentComponent implements OnInit {
    @Select(ReservationLentState.getReservationLent) reservationLent$: Observable<WarehouseItemAllLentOutput[]>;
    @Select(ReservationLentState.getWarehouseAll) warehouses$: Observable<WarehouseAllOutput[]>;
    @Select(ReservationLentState.isLoading) isLoading$: Observable<boolean>;
    reservationLent: WarehouseItemAllLentOutput[];
    warehouses: WarehouseAllOutput[];
    othersIsLoading: boolean;

    sortingTypes: Array<{ id: number, name: string }> = [
        { id: 1, name: 'Názvu' },
        { id: 2, name: 'Od nejnovějšího' }
    ];
    chosenSortType: string;

    constructor(
        private router: Router,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private modalService: ModalDialogService,
        private viewContainerRef: ViewContainerRef
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (this.router.url === '/material/reservationLent') {
                    this.othersIsLoading = false;
                }
            }
        });
        this.chosenSortType = this.sortingTypes[0].name;
    }

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadWarehouseAll())
            .pipe(withLatestFrom(this.warehouses$))
            .subscribe(([_, warehouses]) => {
                this.warehouses = warehouses;
                this.store.dispatch(new LoadWarehouseItemAllLent())
                    .pipe(withLatestFrom(this.reservationLent$))
                    .subscribe(([_, reservations]) => {
                        this.reservationLent = reservations.filter(reservation =>
                            this.warehouses.map(w => w.ID).indexOf(reservation.ID_WarehouseItemReservationDestination) === -1);
                        this.sortReservations(this.sortingTypes.find(st => st.name === this.chosenSortType));

                    }, err => {
                        feedbackMessage(FeedbackType.Error, 'Načtení půjčených položek', 'Nepodařilo se načíst půjčené položky.');
                        console.log(err);
                    });
                }, err => {
                feedbackMessage(FeedbackType.Error, 'Načtení skladů', 'Nepodařilo se načíst sklady.');
                console.log(err);
            });

    }

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

    onTapItem(reservation: WarehouseItemAllLentOutput) {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/materialDetail', reservation.ID], {transition: transitionOptions});
        }, 10);
    }

    onSortTap() {
        const options = {
            message: 'Seřadit podle',
            cancelButtonText: 'Zrušit',
            actions: this.sortingTypes.map(st => st.name)
        };

        action(options).then(async (result) => {
            this.sortReservations(this.sortingTypes.find(st => st.name === result));
            this.chosenSortType = result;
        });
    }

    sortReservations(type: {id: number, name: string}) {

        switch (type.id) {
            case 1:
                this.reservationLent.sort((a, b) => {
                    return a.DisplayName.toLowerCase()
                        .localeCompare(b.DisplayName.toLowerCase(), 'cs', {
                        numeric: true,
                        sensitivity: 'base'
                        });
                    });
                break;
            case 2:
                this.reservationLent.sort((a, b) => b.ID - a.ID);
                break;
        }

    }

    showModalHelp() {
        this.othersIsLoading = true;
        const options: ModalDialogOptions = {
            viewContainerRef: this.viewContainerRef,
            context: {
                label: 'Vydané položky',
                messages: ['Zde naleznete přehled všech položek, které jste někomu půjčil(a). Objeví se zde po vydání položky na stránce detailu dané položky.',
                    'Vydat položku lze pouze v případě, že položka zrovna není vypůjčena a je na ní vytvořena alespoň jedna čekající rezervace.']
            },
            fullscreen: false
        };
        this.othersIsLoading = false;
        this.modalService.showModal(ModalHelpComponent, options);
    }

    get helpIcon() {
        return String.fromCharCode(0xf059);
    }
}
