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

import { LocaleCode } from '@ucap/core';

import { PasswordUtil } from '@ucap/pi';

import {
  SessionStorageService,
  LocalStorageService
} from '@ucap/ng-web-storage';
import { NativeService } from '@ucap/native';

import { UCAP_NATIVE_SERVICE } from '@ucap/ng-native';

import { LoginSession } from '@app/models/login-session';
import { UserStore } from '@app/models/user-store';

import { AppKey } from '@app/types/app-key.type';

import { environment } from '@environments';

@Injectable({
  providedIn: 'root'
})
export class AppAuthenticationService {
  constructor(
    private sessionStorageService: SessionStorageService,
    private localStorageService: LocalStorageService,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService
  ) {}

  loggedIn(): boolean {
    const loginSession = this.sessionStorageService.get<LoginSession>(
      AppKey.LoginSession
    );
    return null !== loginSession && !!loginSession.loginId;
  }

  async login(
    loginSession: LoginSession,
    rememberMe: boolean,
    autoLogin: boolean
  ) {
    loginSession = { ...loginSession, localeCode: LocaleCode.Korean };
    const encLoginPw = PasswordUtil.encrypt(loginSession.loginPw);

    this.sessionStorageService.set<LoginSession>(AppKey.LoginSession, {
      ...loginSession,
      initPw: loginSession.loginId === loginSession.loginPw,
      loginPw: encLoginPw
    });

    let userStore = this.localStorageService.encGet<UserStore>(
      AppKey.UserStore,
      environment.productConfig.localEncriptionKey
    );

    if (!userStore) {
      userStore = {
        idleCheckTime: 10,
        settings: {
          ...environment.productConfig.defaultSettings,
          chat: {
            ...environment.productConfig.defaultSettings.chat,
            downloadPath: await this.nativeService.getPath(
              'documents',
              environment.productConfig.file.defaultDownloadFolder
            )
          }
        }
      };

      if (!!environment.productConfig.defaultSettings.general.autoLaunch) {
        this.nativeService.changeAutoLaunch(
          environment.productConfig.defaultSettings.general.autoLaunch
        );
      }
    }

    userStore = {
      ...userStore,
      companyGroupType: loginSession.companyGroupType,
      companyCode: loginSession.companyCode,
      loginId: loginSession.loginId,
      loginPw: loginSession.loginPw
    };

    if (rememberMe || autoLogin) {
      userStore = {
        ...userStore,
        rememberMe
      };
      userStore.settings.general.autoLogin = autoLogin;
    }

    this.localStorageService.encSet<UserStore>(
      AppKey.UserStore,
      userStore,
      environment.productConfig.localEncriptionKey
    );

    this.sessionStorageService.remove(AppKey.LogoutSession);
  }

  logout() {
    this.sessionStorageService.remove(AppKey.LoginResponse);
    this.sessionStorageService.remove(AppKey.VerInfoResponse);
    this.sessionStorageService.remove(AppKey.LoginSession);
    this.sessionStorageService.remove(AppKey.UrlInfoResponse);
    this.sessionStorageService.remove(AppKey.AuthResponse);

    let userStore = this.localStorageService.encGet<UserStore>(
      AppKey.UserStore,
      environment.productConfig.localEncriptionKey
    );

    if (!!userStore) {
      userStore = {
        ...userStore,
        settings: {
          ...userStore.settings,
          general: {
            ...userStore.settings.general,
            autoLogin: false
          }
        }
      };

      this.localStorageService.encSet<UserStore>(
        AppKey.UserStore,
        userStore,
        environment.productConfig.localEncriptionKey
      );
    }
  }
}
