import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { PageRoute, RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { switchMap, withLatestFrom } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { WarehouseDetailOutput } from '../../entities/output/warehouseDetailOutput';
import { WarehouseItemAllOutput } from '../../entities/output/warehouseItemAllOutput';
import { LoadWarehouseDetail, LoadWarehouseItemAll } from '../../state-mgmt/warehouse-detail.action';
import { WarehouseDetailState } from '../../state-mgmt/warehouse-detail.state';
import { feedbackMessage } from '../../utils/feedback-messages';

@Component({
    selector: 'WarehouseDetail',
    moduleId: module.id,
    templateUrl: './warehouse-detail.component.html',
    styleUrls: ['./warehouse-detail.component.scss']
})

export class WarehouseDetailComponent implements OnInit {
    @Select(WarehouseDetailState.getWarehouseDetail) warehouse$: Observable<WarehouseDetailOutput>;
    @Select(WarehouseDetailState.getWarehouseItems) items$: Observable<WarehouseItemAllOutput[]>;
    @Select(WarehouseDetailState.isLoading) isLoading$: Observable<boolean>;
    warehouse: WarehouseDetailOutput;
    items: WarehouseItemAllOutput[];
    othersIsLoading: boolean;

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

    onLoad() {
        this.pageRoute.activatedRoute
        .pipe(
            switchMap(activatedRoute => activatedRoute.params)
        )
        .forEach((params) => {
            this.store.dispatch(new LoadWarehouseDetail(+params['id']))
                .pipe(withLatestFrom(this.warehouse$))
                .subscribe(([_, warehouseDetail]) => {
                    this.warehouse = warehouseDetail;
                    this.store.dispatch(new LoadWarehouseItemAll([+params['id']]))
                        .pipe(withLatestFrom(this.items$))
                        .subscribe(([_, items]) => {
                            this.items = items.sort((item1, item2) => {
                                return item1.DisplayName.toLowerCase()
                                    .localeCompare(item2.DisplayName.toLowerCase(), 'cs', {
                                    numeric: true,
                                    sensitivity: 'base'
                                });
                            });
                        }, err => {
                            feedbackMessage(FeedbackType.Error, 'Načtení položek skladu', 'Nepodařilo se načíst položky skladu.');
                            console.log(err);
                        });
                }, err => {
                    this.warehouse = null;
                    feedbackMessage(FeedbackType.Error, 'Načtení detailu skladu', 'Nepodařilo se načíst detail skladu.');
                    console.log(err);
                });
            });
    }

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

    onUnitTap() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['unit', this.warehouse.ID_Unit], {transition: transitionOptions});
        }, 10);
    }

    onWarehouseMainTap() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/warehouseDetail', this.warehouse.ID_WarehouseMain], {transition: transitionOptions});
        }, 10);
    }

    onUpdateTap() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/warehouseUpdate', this.warehouse.ID], {transition: transitionOptions});
        }, 10);
    }

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

    newItem() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/materialNew', this.warehouse.ID], {transition: transitionOptions});
        }, 10);
    }

    get newIcon() {
        return String.fromCharCode(0xf271);
    }

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

    get updateIcon() {
        return String.fromCharCode(0xf044);
    }

}
