import { Injectable } from '@angular/core';
import { AES, enc, SHA1 }  from  'crypto-js'

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

  private prefix = 'v17-'

  constructor() {

    const key =  SHA1('version').toString()
    this.set(key, this.prefix)
  }

  getKey(keyName:string) {
    return this.prefix + keyName
  }

  get( keyName:string, safe) {

    keyName = this.getKey(keyName)

    const ciphertext = localStorage.getItem(keyName)

    const hashKey = SHA1(keyName).toString()

    if(ciphertext) {
      const bytes   = AES.decrypt(ciphertext, hashKey)
      var decryptedData = bytes.toString(enc.Utf8);
      try {
        return JSON.parse(decryptedData)
      } catch {
        return decryptedData;
      }

    } else {
      return safe
    }
  }

  set(keyName:string, value) {

    keyName = this.getKey(keyName)

    if(typeof(value) != 'string') {
      value = JSON.stringify(value)
    }

    const hashKey = SHA1(keyName).toString()

    const data = value
    const encoded = AES.encrypt( data, hashKey).toString();
    localStorage.setItem(keyName, encoded)
  }

  delete(keyName:string) {

    keyName = this.getKey(keyName)
    localStorage.removeItem(keyName)
  }

}

export const localstoreService = new LocalstoreService()