import { Injectable } from '@angular/core';
import CryptoJS from 'crypto-js';
import crypto from 'crypto';

import { CipherUtil } from '../utils/CipherUtil';

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

  encrypt(pvUserKey: string, pvSource: string, isBase64: string): string {
    const cipherKeyDTD = CipherUtil.makeCipherKey('AES', pvUserKey);

    const cipher = crypto.createCipheriv(
      'aes-128-cbc',
      cipherKeyDTD.key,
      cipherKeyDTD.iv
    );
    cipher.setAutoPadding(true);

    let outputEncoding: 'base64' | 'hex';

    if ('Y' === isBase64) {
      outputEncoding = 'base64';
    } else {
      outputEncoding = 'hex';
    }

    const cipherChunks = [];
    cipherChunks.push(cipher.update(pvSource, 'utf8', outputEncoding));
    cipherChunks.push(cipher.final(outputEncoding));

    return cipherChunks.join('');
  }

  encryptForWebLink(pvSource: string): string {
    return CryptoJS.SHA1(pvSource)
      .toString()
      .toUpperCase();
  }
}
