import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  Router
} from '@angular/router';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

import {
  LocalStorageService,
  SessionStorageService
} from '@ucap-webmessenger/web-storage';
import { AppUserInfo, KEY_APP_USER_INFO } from '@app/types/app-user-info.type';
import { environment } from '../../environments/environment';
import * as AuthenticationStore from '@app/store/account/authentication';
import { KEY_LOGOUT_INFO, LogoutInfo } from '@app/types';

@Injectable({
  providedIn: 'root'
})
export class AppAutoLoginGuard implements CanActivate {
  constructor(
    private router: Router,
    private store: Store<any>,
    private localStorageService: LocalStorageService,
    private sessionStorageService: SessionStorageService
  ) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    return new Promise<boolean | UrlTree>((resolve, reject) => {
      const appUserInfo = this.localStorageService.encGet<AppUserInfo>(
        KEY_APP_USER_INFO,
        environment.customConfig.appKey
      );

      const personLogout: LogoutInfo = this.sessionStorageService.get(
        KEY_LOGOUT_INFO
      );

      if (
        !!appUserInfo &&
        appUserInfo.settings.general.autoLogin &&
        !(!!personLogout && !!personLogout.personLogout)
      ) {
        this.store.dispatch(
          AuthenticationStore.webLogin({
            loginInfo: {
              companyCode: appUserInfo.companyCode,
              companyGroupType: appUserInfo.companyGroupType,
              loginId: appUserInfo.loginId,
              loginPw: appUserInfo.loginPw
            },
            rememberMe: appUserInfo.rememberMe,
            autoLogin: true
          })
        );
        resolve(false);
      } else {
        resolve(true);
      }
    });
  }
}
