const Constants = require('../../constants');
const fs = require('fs');
const helpers = require('../../helpers');
const os = require('os');

const addListeners = (ipcMain, {setIsInstalling, unmountAllDrives, standardIPCReply}) => {
  ipcMain.on(Constants.IPC_Install_Upgrade, (event, data) => {
    let allowSkipVerification = true;

    unmountAllDrives();

    let tempSig;
    let tempPub;
    const cleanupFiles = () => {
      try {
        if (tempSig) {
          fs.unlinkSync(tempSig);
        }
        if (tempPub) {
          fs.unlinkSync(tempPub);
        }
      } catch (e) {
      }
    };

    const errorHandler = err => {
      cleanupFiles();
      setIsInstalling(false);
      standardIPCReply(event, Constants.IPC_Install_Upgrade_Reply, {
        AllowSkipVerification: allowSkipVerification,
        Source: data.Source,
      }, err);
    };

    // TODO Enable verification in 1.0.4
    const hasSignature = false;//!data.SkipVerification && data.Signature && (data.Signature.length > 0);
    const hasHash = false;//!data.SkipVerification && data.Sha256 && (data.Sha256.length > 0);
    if (hasSignature) {
      try {
        const files = helpers.createSignatureFiles(data.Signature, Constants.DEV_PUBLIC_KEY);
        tempPub = files.PublicKeyFile;
        tempSig = files.SignatureFile;
      } catch (e) {
        errorHandler(e);
        return;
      }
    }

    let command;
    let args;
    const platform = os.platform();
    if (platform === 'win32') {
      command = data.Source;
    } else if (platform === 'darwin') {
      command = 'open';
      args = ['-a', 'Finder', data.Source];
    } else if (platform === 'linux') {
      try {
        command = data.Source;
        fs.chmodSync(command, '750');
      } catch (e) {
        errorHandler(e);
      }
    } else {
      errorHandler(Error('Platform not supported: ' + os.platform()));
    }

    if (command) {
      const executeInstall = () => {
        setIsInstalling(true);
        helpers
        .executeAsync(command, args)
        .then(() => {
          cleanupFiles();
          standardIPCReply(event, Constants.IPC_Install_Upgrade_Reply)
        })
        .catch(error => {
          setIsInstalling(false);
          errorHandler(error);
        });
      };

      if (hasSignature) {
        helpers
        .verifySignature(data.Source, tempSig, tempPub)
        .then(() => {
          executeInstall();
        })
        .catch(() => {
          errorHandler(Error('Failed to verify installation package signature'));
        });
      } else if (hasHash) {
        helpers
        .verifyHash(data.Source, data.Sha256)
        .then(()=> {
          executeInstall();
        })
        .catch(() => {
          errorHandler(Error('Failed to verify installation package hash'));
        });
      } else {
        if (platform === 'darwin') {
          setTimeout(executeInstall, 3000);
        } else {
          executeInstall();
        }
      }
    } else {
      errorHandler(Error('Unsupported upgrade: ' + data.Source));
    }
  });
};

module.exports = {
  addListeners
};
