import { Injectable } from '@angular/core';
import { EmployeeModel, MyEmployeeModel } from '../model/employee.model';
import { Router } from '@angular/router';
import { UserModel } from '../model/user.model';

const TOKEN_KEY = 'auth-token';
const REFRESHTOKEN_KEY = 'auth-refreshtoken';
const USER_KEY = 'auth-user';
const USER_DATA_KEY = 'auth-user-data';
export interface UserLoginModel {
  sub: string;
  iss: string;
  companyid: string;
  companyName: string;
  employeeid: string;
  dbName: string;
  job: string;
  emp_position: string;
  user_level: string;
  lang: string;
  firstlogin: string;
  user_role: string;
  role_level: string;
  encode: string;
  user: string;
  roles: string[];
  username: string;
  app_name: string;
  zmlogin: string;
  zm_user: string;
  memberid: string;
  token_zeeme: string;
  comid: string;
  url_myhr: string;
  regionallty: string;
  ad: string;
  workarea: string;
  branch: string;
  actorid: string;
  accountactive: string;
  exp: number;
}

@Injectable({
  providedIn: "root",
})
export class TokenService {
  constructor(private router: Router) { }

  signOut(): void {
    window.localStorage.clear();
    localStorage.clear();
    sessionStorage.clear()
    this.router.navigate(['/auth/login']);
  }

  public saveToken(token: string): void {
    window.localStorage.removeItem(TOKEN_KEY);
    window.localStorage.setItem(TOKEN_KEY, token);
    sessionStorage.setItem("accessToken", token)
  }

  public saveUser(user: any): void {
    window.localStorage.removeItem(USER_KEY);
    window.localStorage.setItem(USER_KEY, JSON.stringify(user));
  }

  public getUser(): UserLoginModel | undefined {
    const user = window.localStorage.getItem(USER_KEY);
    if (user) {
      return JSON.parse(user);
    }

    return undefined;
  }

  public getToken(): string | null {
    return window.localStorage.getItem(TOKEN_KEY);
  }

  public saveRefreshToken(token: string): void {
    window.localStorage.removeItem(REFRESHTOKEN_KEY);
    window.localStorage.setItem(REFRESHTOKEN_KEY, token);
  }

  public getRefreshToken(): string | null {
    return window.localStorage.getItem(REFRESHTOKEN_KEY);
  }
  public saveUserData(user: EmployeeModel): void {
    window.localStorage.removeItem(USER_DATA_KEY);
    window.localStorage.setItem(USER_DATA_KEY, JSON.stringify(user));
  }

  public getUserData(): EmployeeModel {
    // return window.localStorage.getItem(USER_DATA_KEY);
    const user = window.localStorage.getItem(USER_DATA_KEY);
    if (user) {
      return new MyEmployeeModel(JSON.parse(user));
    }

    return new MyEmployeeModel();
  }

}
