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 { EnrollNumberAllPersonOutput } from '~/pages/sts/entities/output/enrollNumberAllPersonOutput';
import { LoadEnrollNumbers } from '~/pages/sts/state-mgmt/sts.actions';
import { StsState } from '~/pages/sts/state-mgmt/sts.state';

@Component({
    selector: 'Sts',
    moduleId: module.id,
    templateUrl: './sts.component.html',
    styleUrls: ['./_sts.component.scss']
})
export class StsComponent implements OnInit {
    @Select(StsState.getEnrollNumbers) enrollNumbers$: Observable<EnrollNumberAllPersonOutput[]>;
    @Select(StsState.isLoading) isLoading$: Observable<boolean>;
    enrollNumbers: EnrollNumberAllPersonOutput[];
    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 === '/sts') {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    ngOnInit() {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadEnrollNumbers());
        this.enrollNumbers$.subscribe(enrollNumbers => this.enrollNumbers = enrollNumbers);
    }

    onDisplayCostsStat() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['/sts/stats'], { transition: transitionOptions });
        }, 10);
    }

    onItemTap(enrollNumber: string) {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['/sts/detail', enrollNumber], { transition: transitionOptions });
        }, 10);
    }

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

    get statsIcon() {
        return String.fromCharCode(0xf080);
    }
}
