import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { HttpService } from '../shared/services/http.service';
import { MiscService } from '../shared/services/misc.service';
import { Router } from '@angular/router';
import { User } from '../models/user';
import { HttpErrorResponse } from '@angular/common/http';
import { CONSTANTS } from '../utils/app.constants';
import { StorageService } from '../shared/services/storage.service';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private httpService: HttpService, private miscService: MiscService, private router: Router, private storageService: StorageService) { }
  firstLogin: boolean = false;
  private token: string = "";

  async login(User_Data: User) {
    let login = false;
    let userId = User_Data.Username;
    let password = User_Data.Password;
    let data = { "userId": userId, "password": password};

    let url = '/authentication/login';

    let response: any = await this.httpService.postRequest(url, data)!.toPromise();
    if (!(response instanceof HttpErrorResponse)) {
      if ((await response["errorMessage"] == undefined)) {
        if (response) {
          login = true;
          localStorage.setItem('userId', userId);
          let res = JSON.parse(JSON.stringify(response));
          // let permission = JSON.parse(res['userPermission']);
          // localStorage.setItem('SIDENAV', res['userPermission']);
          localStorage.setItem('userFullname', res.user.userFullname);
          localStorage.setItem('userId', res.user.userId);
          localStorage.setItem('token', res.token);
          this.firstLogin = response.requiresPasswordChange;
          this.storageService.setItem('firstLogin', this.firstLogin ? 'true' : 'false');
          return res;
          
        }
      }
      let res = response;
      return res;

    }
  }

  IsLoggedIn() {
    if (this.storageService.getItem('userId') !== null)
      return true;
    else
      return false;
  }

  logout() {
    window.history.state;
    localStorage.clear();
    this.router.navigate(['login'])
  }

  getToken(): string {
    this.token = localStorage.getItem('token') || "";
    return this.token;
  }

  setToken(token: string) {
    this.token = token;
    localStorage.setItem('token', token);
  }

  refreshToken() {
    let uCreds = { token: this.getToken() };
    let porOrgacode = CONSTANTS.POR_ORGACODE;
    let refreshTokenData: any = {
      cmpUserId: localStorage.getItem('userId'),
      token: uCreds.token,
      porOrgacode: porOrgacode
    }
    return this.httpService.postRequest("/refreshToken", refreshTokenData)!.pipe(
      tap((response: any) => {
        localStorage.removeItem('token')
        localStorage.setItem('token', JSON.stringify(response.token));
        this.setToken(response.token);
      })
    );
  }
}
