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-borrowed.action';
import { ReservationBorrowedState } from '../../state-mgmt/reservation-borrowed.state';
import { feedbackMessage } from '../../utils/feedback-messages';

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

export class ReservationBorrowedComponent implements OnInit {
    @Select(ReservationBorrowedState.getReservationBorrowed) reservationBorrowed$: Observable<WarehouseItemAllLentOutput[]>;
    @Select(ReservationBorrowedState.getWarehouseAll) warehouses$: Observable<WarehouseAllOutput[]>;
    @Select(ReservationBorrowedState.isLoading) isLoading$: Observable<boolean>;
    reservationBorrowed: WarehouseItemAllLentOutput[];
    warehouses: WarehouseAllOutput[];
    othersIsLoading: boolean;

    sortingTypes: Array<{ id: number, name: string }> = [
        { id: 1, name: 'Názvu' },
        { id: 2, name: 'Stavu' },
        { id: 3, 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/reservationBorrowed') {
                    this.othersIsLoading = false;
                }
            }
        });
        this.chosenSortType = this.sortingTypes[0].name;
    }

    onLoad() {
        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.reservationBorrowed$))
                    .subscribe(([_, reservations]) => {
                        this.reservationBorrowed = 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);
            });
    }

    ngOnInit(): void {
        this.othersIsLoading = false;
    }

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

    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.reservationBorrowed.sort((a, b) => {
                    return a.DisplayName.toLowerCase()
                        .localeCompare(b.DisplayName.toLowerCase(), 'cs', {
                        numeric: true,
                        sensitivity: 'base'
                        });
                    });
                break;
            case 2:
                const priorityList = ['Půjčeno', 'Rezervováno', 'Čeká na vyřízení', 'Vráceno', 'Zrušeno'];
                this.reservationBorrowed.sort((a, b) => {
                    const res = priorityList.indexOf(a.State) - priorityList.indexOf(b.State);
                    if (res === 0) {
                        return a.DisplayName.toLowerCase()
                        .localeCompare(b.DisplayName.toLowerCase(), 'cs', {
                        numeric: true,
                        sensitivity: 'base'
                        });
                    }

                    return res;
                });
                break;
            case 3:
                this.reservationBorrowed.sort((a, b) => b.ID - a.ID);
                break;
        }

    }

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

    showModalHelp() {
        this.othersIsLoading = true;
        const options: ModalDialogOptions = {
            viewContainerRef: this.viewContainerRef,
            context: {
                label: 'Rezervováno/vypůjčeno',
                messages: ['Zde naleznete přehled všech položek, které jste si rezervovali (tzn. ty, které Vám již byly půjčeny i ty, které čekají na vyřízení).',
                    'Pokud Vaše rezervace ještě nebyla vyřízena, je možné ji upravit nebo zrušit.']
            },
            fullscreen: false
        };
        this.othersIsLoading = false;
        this.modalService.showModal(ModalHelpComponent, options);
    }

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