import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { PageRoute, RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { FunctionAllOutput } from '~/pages/unit/entities/output/functionAllOutput';
import { UnitContactAllOutput } from '~/pages/unit/entities/output/unitContactAllOutput';
import { UnitDetailOutput } from '~/pages/unit/entities/output/unitDetailOutput';
import { UnitTreeAllOutput } from '~/pages/unit/entities/output/unitTreeAllOutput';
import { UnitService } from '~/shared/services/unit.service';
// detail
import { LoadUnitContacts, LoadUnitDetail, LoadUnitFunctions } from '~/pages/unit/state-mgmt/unit-detail.actions';
import { UnitDetailState } from '~/pages/unit/state-mgmt/unit-detail.state';
import { ActionsExecuting, actionsExecuting } from '@ngxs-labs/actions-executing';

@Component({
    selector: 'Unit',
    moduleId: module.id,
    templateUrl: './unit.component.html',
    styleUrls: ['./_unit.component.scss']
})
export class UnitComponent implements OnInit {
    @Select(UnitDetailState.getUnitDetail) unitDetail$: Observable<UnitDetailOutput>;
    @Select(UnitDetailState.getUnitFunctions) unitFunctions$: Observable<FunctionAllOutput[]>;
    @Select(UnitDetailState.getUnitContacts) unitContacts$: Observable<UnitContactAllOutput[]>;

    @Select(actionsExecuting([
        LoadUnitDetail, LoadUnitFunctions, LoadUnitContacts
    ]))
    isLoading$: Observable<ActionsExecuting>;

    unitId: number;
    unitDetail: UnitDetailOutput;
    parentUnitName$: Observable<string>;
    unitTree$: Observable<UnitTreeAllOutput[]>;
    othersIsLoading: boolean;
    functions: FunctionAllOutput[];

    constructor(
        private router: Router,
        protected route: ActivatedRoute,
        private routerExtensions: RouterExtensions,
        private unitService: UnitService,
        private store: Store
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (RegExp('\/unit\/[0-9]+').test(this.router.url)) {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    get membersIcon() {
        return String.fromCharCode(0xf0c0);
    }

    onNavTap(navRoute: string, unitId: number) {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate([navRoute, unitId], { transition: transitionOptions });
        }, 10);
    }

    onItemTap(unitId: number) {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['unit', unitId], { transition: transitionOptions });
        }, 10);
    }

    onTapAll() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['unit/functions', this.unitId], { transition: transitionOptions });
        }, 10);
    }

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

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

    get existUnitAddress() {
        return this.unitDetail && this.unitDetail.Street && this.unitDetail.City && this.unitDetail.Postcode;
    }

    get existPostalAddress() {
        return this.unitDetail && this.unitDetail.PostalFirstLine && this.unitDetail.PostalStreet && this.unitDetail.PostalCity && this.unitDetail.PostalPostcode;
    }

    /**
     * In hook I dispatch action for loading data using unitId from params.
     * It subscribe data too. IsLoading property is her in setTimeout wraper due to error of ExpressionChangedAfterItHasBeenCheckedError
     */
    ngOnInit(): void {
        this.othersIsLoading = false;
        this.route.params.subscribe(params => {
            this.unitId = +params['unitId'];
            if (this.unitId) {
                this.store.dispatch([
                    new LoadUnitDetail(this.unitId),
                    new LoadUnitFunctions(this.unitId),
                    new LoadUnitContacts(this.unitId)
                ]).pipe(withLatestFrom(this.unitDetail$, this.unitFunctions$))
                    .subscribe(([_, detail, functions]) => {
                        this.unitDetail = detail;
                        this.functions = functions;
                        if (detail && detail.ID_UnitParent !== 0) {
                            this.parentUnitName$ = this.unitService.getParentUnitName(this.unitDetail.ID_UnitParent);
                        }
                    })
            }
        })
        // Get list of subordinate units
        this.unitTree$ = this.unitService.getUnitTree(this.unitId);
    }
}
