import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { PageRoute, RouterExtensions } from '@nativescript/angular';
import { ListViewEventData } from 'nativescript-ui-listview';
import { switchMap } from 'rxjs/operators';
import { WarehouseItemAllOutput } from '../../entities/output/warehouseItemAllOutput';
import { DatabaseService } from '../../services/database.service';

@Component({
    selector: 'InventoryConfirmed',
    moduleId: module.id,
    templateUrl: './inventory-confirmed.component.html',
    styleUrls: ['./inventory-confirmed.component.scss']
})

export class InventoryConfirmedComponent implements OnInit {
    @ViewChild('list', { static : true}) list: ElementRef;

    idWarehouse: number;
    items: WarehouseItemAllOutput[];
    othersIsLoading: boolean;
    isAnyIDLast: boolean = false;

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

    ngOnInit(): void {
        this.othersIsLoading = false;
        // this.database.deleteAllItems();
        this.pageRoute.activatedRoute
            .pipe(
                switchMap(activatedRoute => activatedRoute.params)
            )
            .forEach((params) => {
                this.idWarehouse = +params['id'];
            });

        this.database.loadItems(this.idWarehouse)
                .then((items: WarehouseItemAllOutput[]) => {
                    this.items = items.filter(i => i.localChange === false && i.idLastInventory)
                        .sort((item1, item2) => {
                            return item1.DisplayName.toLowerCase()
                                .localeCompare(item2.DisplayName.toLowerCase(), 'cs', {
                                numeric: true,
                                sensitivity: 'base'
                            });
                        });
                    this.isAnyIDLast = this.items.find(i => i.idLastInventory !== null) !== undefined;
                });
    }

    onTapItem(event: ListViewEventData) {
        this.items[event.index].expanded = !this.items[event.index].expanded;
    }

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

    templateSelector(): string {
        return 'default';
    }

    get downIcon() {
        return String.fromCharCode(0xf107);
    }

    get rightIcon() {
        return String.fromCharCode(0xf105);
    }
}
