import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { ApplicationSettings } from '@nativescript/core';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { wsUserManagement } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { transitionOptions } from '~/constants/shared.constants';
import { LoginUpdateRefresh } from '~/core/entities/input/loginUpdateRefresh';
import { LoginUpdateRefreshOutput } from '~/core/entities/output/loginUpdateRefreshOutput';
import { LoginDataService } from '~/core/services/login-data.service';
import { WebApiService } from '~/core/services/web-api.service';
import { AppState } from '~/core/state-mgmt/app.state';

@Component({
    selector: 'Home',
    moduleId: module.id,
    templateUrl: './home.component.html',
    styleUrls: ['./_home.component.scss']
})
export class HomeComponent implements OnInit {
    @Select(AppState.isLoading) isLoading$: Observable<boolean>;
    isLoading: boolean;
    othersIsLoading: boolean;
    userData: any = null;

    constructor(
        private router: Router,
        private routerExtensions: RouterExtensions,
        private _changeDetectionRef: ChangeDetectorRef,
        private loginDataSrv: LoginDataService,
        private webApiSrv: WebApiService
    ) {
    }

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.webApiSrv.call(
            new LoginUpdateRefresh(ApplicationSettings.getString(USER_TOKEN)) as any,
            () => new LoginUpdateRefreshOutput(),
            wsUserManagement
        ).toPromise()
            .then(() => {
                this.loginDataSrv.updateUserData();
                setTimeout(() => {
                    this.loginDataSrv.updateUserData();
                });
            })
            .catch(err => {
                this.loginDataSrv.logout();
            });

        this.isLoading$.subscribe(isLoading => {
            setTimeout(() => {
                this.isLoading = isLoading;
            });
        });
    }

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

    templateSelector(item: any, index: number, items: any): string {
        return 'default';
    }
}
