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 { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { FunctionAllOutput } from '~/pages/unit/entities/output/functionAllOutput';
import { LoadUnitFunctions } from '~/pages/unit/state-mgmt/unit-functions.actions';
import { UnitFunctionsState } from '~/pages/unit/state-mgmt/unit-functions.state';

@Component({
    selector: 'UnitFunctions',
    moduleId: module.id,
    templateUrl: './unit-functions.component.html',
    styleUrls: ['./_unit-functions.component.scss']
})
export class UnitFunctionsComponent implements OnInit {
    @Select(UnitFunctionsState.getUnitFunctions) unitFunctions$: Observable<FunctionAllOutput[]>;
    @Select(UnitFunctionsState.isLoading) isLoading$: Observable<boolean>;
    unitId: number;
    unitFunctions: FunctionAllOutput[];
    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('\/unit\/functions\/[0-9]+').test(this.router.url)) {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    /**
     * In hook I dispatch action for loading data using unitId from params.
     * It subscribe data too.
     *
     */
    ngOnInit(): void {
        this.othersIsLoading = false;
        this.pageRoute.activatedRoute
            .pipe(
                switchMap(activatedRoute => activatedRoute.params)
            )
            .forEach((params) => {
                this.unitId = +params['unitId'];

                if (this.unitId) {
                    this.store.dispatch(new LoadUnitFunctions(this.unitId));
                }
            });
        this.unitFunctions$.subscribe(unitFunctions => this.unitFunctions = unitFunctions);
    }

    onItemTap(personId: number) {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['search/list', personId, false], { transition: transitionOptions });
        }, 10);
    }

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