import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { transitionOptions } from '~/constants/shared.constants';
import { MySearchPerson } from '~/pages/search-person/entities/my-search-person';
import { LoadCatalogPersons, LoadPersons } from '~/pages/search-person/state-mgmt/search-person-list.actions';
import { SearchPersonListState } from '~/pages/search-person/state-mgmt/search-person-list.state';

@Component({
    selector: 'SearchPersonList',
    moduleId: module.id,
    templateUrl: './search-person-list.component.html',
    styleUrls: ['./_search-person-list.component.scss']
})
export class SearchPersonListComponent implements OnInit {
    @Select(SearchPersonListState.isLoading) isLoading$: Observable<boolean>;
    @Select(SearchPersonListState.getSearchPersons) searchPersons$: Observable<MySearchPerson[]>;
    searchPersons: MySearchPerson[];
    othersIsLoading: boolean;

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

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadPersons());
        this.store.dispatch(new LoadCatalogPersons());
        this.searchPersons$.subscribe(searchPersons => this.searchPersons = searchPersons);
    }

    onShowPerson(person: MySearchPerson) {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['search/list', person.personId, person.isCatalog], {transition: transitionOptions});
        }, 10);
    }

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