import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { ApplicationSettings } from '@nativescript/core';
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 './web-api.service';

/**
 * Service takes care of authentization user for agends
 * AuthGuard protect Unit, Sts, Search agends only for login user. If User is not login, it navigate to login page
 */
@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private routerExtensions: RouterExtensions,
        private webApiSrv: WebApiService,
        private loginDataSrv: LoginDataService
    ) {
    }

    /**
     * It find out if user is loged in and according to it return Promise<boolean>
     *
     * @returns {Promise<boolean>}
     */
    async canActivate(): Promise<boolean> {
        return this.webApiSrv.call(
            new LoginUpdateRefresh(ApplicationSettings.getString(USER_TOKEN)) as any,
            () => new LoginUpdateRefreshOutput(),
            wsUserManagement
        ).toPromise()
            .then(res => true)
            .catch(err => {
                this.loginDataSrv.logout().then(() => {
                    this.routerExtensions.navigate(['/login'], { transition: transitionOptions });
                });
                return false;
            });
    }
}
