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

import CryptoJS from 'crypto-js';

import {
  SessionStorageService,
  LocalStorageService
} from '@ucap-webmessenger/web-storage';
import { LocaleCode } from '@ucap-webmessenger/core';
import { LoginInfo, KEY_LOGIN_INFO } from '../types';
import { KEY_VER_INFO } from '@app/types/ver-info.type';
import { KEY_LOGIN_RES_INFO } from '@app/types/login-res-info.type';

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

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

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

  login(loginInfo: LoginInfo, rememberMe: boolean) {
    loginInfo = { ...loginInfo, localeCode: LocaleCode.Korean };

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

    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_RES_INFO);
    this.sessionStorageService.remove(KEY_VER_INFO);
    this.sessionStorageService.remove(KEY_LOGIN_INFO);
  }
}
