import { Injectable } from '@angular/core';

import CryptoJS from 'crypto-js';

import {
  SessionStorageService,
  LocalStorageService
} from '@ucap-webmessenger/web-storage';
import { EnviromentUtilService } from '@ucap-webmessenger/util';
import { DeviceType, LocaleCode } from '@ucap-webmessenger/core';
import { LoginInfo, KEY_LOGIN_INFO } from '../types';

@Injectable({
  providedIn: 'root'
})
export class AppAuthenticationService {
  showLoader = false;

  constructor(
    private sessionStorageService: SessionStorageService,
    private localStorageService: LocalStorageService,
    private enviromentUtilService: EnviromentUtilService
  ) {}

  authenticated(): boolean {
    const loginInfo = this.sessionStorageService.get<LoginInfo>(KEY_LOGIN_INFO);
    return null !== loginInfo && !!loginInfo.loginId;
  }

  login(loginInfo: LoginInfo, rememberMe: boolean) {
    let deviceType: DeviceType;

    loginInfo = { ...loginInfo, localeCode: LocaleCode.Korean };

    if (this.enviromentUtilService.nodeWebkit()) {
      deviceType = DeviceType.PC;
    } else if (this.enviromentUtilService.android()) {
      deviceType = DeviceType.Android;
    } else if (this.enviromentUtilService.ios()) {
      deviceType = DeviceType.iOS;
    } else {
      deviceType = DeviceType.Web;
    }

    this.sessionStorageService.set<LoginInfo>(KEY_LOGIN_INFO, {
      ...loginInfo,
      loginPw: CryptoJS.enc.Hex.stringify(CryptoJS.SHA256(loginInfo.loginPw)),
      deviceType
    });

    if (rememberMe) {
      this.localStorageService.set<LoginInfo>(KEY_LOGIN_INFO, {
        ...loginInfo,
        loginPw: undefined
      });
    } else {
      this.localStorageService.remove(KEY_LOGIN_INFO);
    }
  }

  logout() {
    this.sessionStorageService.remove(KEY_LOGIN_INFO);
  }
}
