import { Injectable } from '@angular/core';
import { localstoreService } from './localstore.service'
import { SHA1 }  from  'crypto-js'
import { UserSession } from '../models/user.model';


@Injectable({
  providedIn: 'root'
})
class SessionService {

  // main data
  private _user = new UserSession()
  // local storage keyName
  private keyName: string; 

  constructor() {

    this.keyName = (SHA1(this.constructor.name)).toString()
    let restore = localstoreService.get(this.keyName, {})
    this._user = restore.user || new UserSession()

  }

  get user(): UserSession {
    return this._user  || new UserSession()
  }

  get exist() {
    let restore = localstoreService.get(this.keyName, {})
    let user: UserSession = restore.user
    if(user) {
      if(user.Profile) {
        return true
      }
    }

    return false
  }

  setLoginPreference(loginPreference: 'None' | 'Password' | 'Pin' | null) {
    this._user.LoginPreference = loginPreference
    this.save()
  }

  setPin(pin: string) {
    this._user.PIN = SHA1(pin).toString()
    this.save()
  }

  validatePin(pin: string) {
    return this._user.PIN == SHA1(pin).toString()
  }

  needToValidateUser() {
    return this._user.Inactivity
  }

  setInativity(value: boolean) {
    this._user.Inactivity = value
    this._user.UrlBeforeInactivity = ''
    this.save()
  }

  setUrlBeforeInactivity(pathname: string) {
    this._user.UrlBeforeInactivity = pathname
    this.save()
  }

  get hasPin() {

    if(!this._user.PIN) {
      return false
    }
    return this._user.PIN.length >= 2
    
  }

  reset(user) {
    this._user = user

    this.setInativity(true)
    this.save()
  }

  delete() {
    localstoreService.delete(this.keyName)
    this.reset(new UserSession())
  }

  private save() {

    localstoreService.set(this.keyName, {
      user: this._user
    })

  }
}


export const SessionStore = new SessionService()