import IEncryptable from '@/models/IEncryptable'
import IEncryptPassword from '@/models/IEncryptPassword'
import AES from 'crypto-js/aes'
import utf8 from 'crypto-js/enc-utf8'

const encrypting: boolean = false

class CryptoService {
  public createPassword(): IEncryptPassword {
    return {
      password: this.guid()
    }
  }

  public encrypt(toEncrypt: IEncryptable, password: string): IEncryptable {
    if (!encrypting) {
      return toEncrypt
    }
    const encrypted: IEncryptable = {}
    for (const t in toEncrypt) {
      if (t) {
        encrypted[t] = AES.encrypt(
          toEncrypt[t] && toEncrypt[t].toString(),
          password
        ).toString()
      }
    }
    return encrypted
  }

  public decrypt(encrypted: IEncryptable, password: string): IEncryptable {
    if (!encrypting) {
      return encrypted
    }
    const decrypted: IEncryptable = {}
    for (const t in encrypted) {
      if (t && encrypted[t]) {
        const bytes = AES.decrypt(encrypted[t], password)
        decrypted[t] = bytes.toString(utf8)
      }
    }
    return decrypted
  }

  private guid(): string {
    const s4 = () => {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1)
    }
    return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}`
  }
}

export default new CryptoService()
