const fs = require('fs');
const crypto = require('crypto');

function encode(inputString, downloadFilePath = false) {

  console.log('encod downloadFilePath : ', downloadFilePath)

  var certificatePath = '';

  if(downloadFilePath !== false)
  {
     certificatePath = process.env.DOWNLOAD_PUBLIC_KEY_PATH;
  }
  else{
     certificatePath = process.env.PUBLIC_KEY_PATH;
  }

try {

    const aesKey = crypto.randomBytes(16); // Change the byte length for different key lengths
    const iv = crypto.randomBytes(16); // Initialization vector for AES-CBC

    // Encrypt the file using AES
    const cipher = crypto.createCipheriv('aes-128-cbc', aesKey, iv);
    let encryptedData = cipher.update(inputString);
        encryptedData = Buffer.concat([encryptedData, cipher.final()]);

    // Get the public key from the self-signed certificate
    const publicKey = fs.readFileSync(certificatePath, 'utf-8');  

    // Encrypt the AES key with the public key
    const encryptedAesKey = crypto.publicEncrypt(
    {
      key: publicKey,
      padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',
    },
    aesKey
    );

    // Save the encrypted file and encrypted AES key
   var encryptedResult =  Buffer.concat([encryptedAesKey, iv, encryptedData])
    console.log('File encrypted successfully.');
    console.log('Encrypted String:', encryptedResult);

    if(downloadFilePath !== false)
    {
      try {
        fs.writeFileSync(downloadFilePath, encryptedResult);
        console.log('File downloaded successfully.');
        Swal.fire({
          title: "File Downloaded",
          icon: "success"
        });
      } catch (error) {
        console.error('Error writing file:', error.message);
        	 var errorMessage = "";

        if(error.code == 'EACCES'){

          errorMessage = `Permission Denied.<br> Path: ${downloadFilePath}`;
        }
        else if(error.code == 'ENOENT'){

          errorMessage = `No Such File Directory. <br> Path: ${downloadFilePath}`;
        }
        else{
          errorMessage = `Unknown Error. <br> Path: ${downloadFilePath}`;
        }

          Swal.fire({
            title: "File Download Failed",
            html: errorMessage,
            icon: "warning"
          }); 
                 
      }
    }
    else{

      return encryptedResult;

    }

} catch (error) {

    console.error('Encryption failed:', error.message);
    return null;

}
}

module.exports = encode;
