import { Injectable } from '@angular/core';
import { tokenName } from '@angular/compiler';
import { environment } from 'src/environments/environment';

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

  localStorageKeyToken:string = "hitawod-token";

  constructor() { }

  handle(token:string) {
    this.set(token);
  }

  loggedIn() {
    return this.isValid();
  }

  private set(token:string) {
    localStorage.setItem(this.localStorageKeyToken, token);
  }

  get():string {
    return localStorage.getItem(this.localStorageKeyToken);
  }

  public remove() {
    localStorage.removeItem(this.localStorageKeyToken);
  }

  private isValid() {
    const token = this.get();
    if(token) {
      const payload = this.payload(token);
      if(payload) {
        return payload.iss === `${environment.baseApiUrl}/auth/login` ? true : false;
      }
    }
    return false;
  }

  private payload(token:string) {
    const payload = token.split('.')[1];
    return this.decode(payload);
  }

  private decode(payload) {
    return JSON.parse(atob(payload));
  }

}

