import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { Page, SearchBar } from '@nativescript/core';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { isAndroid } from 'nativescript-platform';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { dismissSoftKeybaord } from '~/core/utils/dismiss-keyboard';
import { latinise } from '~/core/utils/functions';
import { WarehouseAllOutput } from '../../entities/output/warehouseAllOutput';
import { LoadWarehouseAll } from '../../state-mgmt/warehouse-unit.actions';
import { WarehouseUnitState } from '../../state-mgmt/warehouse-unit.state';
import { feedbackMessage } from '../../utils/feedback-messages';

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

export class WarehouseUnitComponent implements OnInit {
    @Select(WarehouseUnitState.getWarehouses) warehouses$: Observable<WarehouseAllOutput[]>;
    @Select(WarehouseUnitState.isLoading) isLoading$: Observable<boolean>;
    warehouses: WarehouseAllOutput[];
    warehousesHolder: WarehouseAllOutput[];
    othersIsLoading: boolean;

    constructor(
        private router: Router,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private page: Page
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (this.router.url === '/material/warehouseUnit') {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    onLoad() {
        this.store.dispatch(new LoadWarehouseAll())
            .pipe(withLatestFrom(this.warehouses$))
            .subscribe(([_, warehouses]) => {
                this.warehouses = warehouses;
                this.warehousesHolder = warehouses;
            }, err => {
                feedbackMessage(FeedbackType.Error, 'Načtení skladů', 'Nepodařilo se načíst sklady.');
                console.log(err);
            });
    }

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

    onSearchLoaded(): void {
        this.searchClearFocus();
    }

    searchClearFocus() {
        const searchBar = <SearchBar>this.page.getViewById('searchBar');
        searchBar.text = '';
        if (isAndroid) {
            searchBar.android.clearFocus();
        }
    }

    onSearchClear(): void {
        this.warehouses = this.warehousesHolder;
    }

    onSearchSubmit(eventData): void {
        const searchBar = eventData.object;
        const searchTerm = searchBar.text.toLowerCase();
        this.warehouses = this.warehousesHolder;
        if (searchTerm !== '') {
            this.warehouses = this.warehouses.filter(item => {
                return latinise(item.DisplayName.toLowerCase()).indexOf(latinise(searchTerm)) !== -1;
            });
        }
    }

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

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