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 { WebApiService } from './web-api.service';

/**
 * Service takes care of access to home page
 * HomeGuard protect Home page only for not login user. If User is login, it navigate to profile page
 */
@Injectable()
export class HomeGuard implements CanActivate {
    constructor(
        private routerExtensions: RouterExtensions,
        private webApiSrv: WebApiService
    ) {
    }

    /**
     * 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 => {
                this.routerExtensions.navigate(['/home/profile'], {transition: transitionOptions});

                return false;
            })
            .catch(err => {
                return true;
            });
    }
}
