import * as Constants from '../../constants';
import {createAction} from '@reduxjs/toolkit';
import {getIPCRenderer} from '../../utils';
import {notifyError} from './error_actions';
import {
  installAndTestRelease,
  installDependency,
  installRelease,
  installUpgrade
} from './install_actions';

export const setAllowDownload = createAction('download/setAllowDownload');

export const SET_DOWNLOAD_BEGIN = 'download/setDownloadBegin';
export const setDownloadBegin = (name, type, url) => {
  return {
    type: SET_DOWNLOAD_BEGIN,
    payload: {
      name,
      type,
      url
    }
  };
};

export const setDownloadEnd = createAction('download/setDownloadEnd');
export const setDownloadProgress = createAction('download/setDownloadProgress');

export const downloadItem = (name, type, urls, isWinFSP, testVersion, appPlatform) => {
  return (dispatch, getState) => {
    if (!Array.isArray(urls)) {
      urls = [urls];
    }

    const downloadComplete = result => {
      if (result.Success) {
        switch (type) {
        case Constants.INSTALL_TYPES.Dependency:
          dispatch(installDependency(result.Destination, result.URL, isWinFSP));
          break;
        case Constants.INSTALL_TYPES.Release:
          dispatch(installRelease(result.Destination));
          break;
        case Constants.INSTALL_TYPES.TestRelease:
          dispatch(installAndTestRelease(result.Destination, testVersion, appPlatform));
          break;
        case Constants.INSTALL_TYPES.Upgrade:
          //const info = this.props.LocationsLookup[this.props.AppPlatform][this.props.VersionLookup[this.props.AppPlatform][0]];
          const sha256 = null;//info.sha256;
          const signature = null;//info.sig;
          dispatch(installUpgrade(result.Destination, sha256, signature, !!result.SkipVerification));
          break;
        default:
          dispatch(notifyError('Unknown download type: ' + type));
          break;
        }
      } else {
        if (type === Constants.INSTALL_TYPES.TestRelease) {
          this.props.setAllowDownload(false);
        }
        dispatch(notifyError(result.Error));
      }
    };

    const downloadAtIndex = index => {
      const url = urls[index];
      const state = getState();
      if ((index > 0) || (!state.download.DownloadActive && state.download.AllowDownload)) {
        const ipcRenderer = getIPCRenderer();
        if (ipcRenderer) {
          dispatch(setDownloadBegin(name, type, url));

          const downloadFileProgress = (_, arg) => {
            dispatch(setDownloadProgress(arg.data.Progress));
          };

          const downloadFileComplete = (_, arg) => {
            ipcRenderer.removeListener(Constants.IPC_Download_File_Progress, downloadFileProgress);
            if (!arg.data.Success && (++index < urls.length)) {
              downloadAtIndex(index);
            } else {
              downloadComplete(arg.data);
              dispatch(setDownloadEnd(arg.data));
            }
          };

          ipcRenderer.on(Constants.IPC_Download_File_Progress, downloadFileProgress);
          ipcRenderer.once(Constants.IPC_Download_File_Complete, downloadFileComplete);

          ipcRenderer.send(Constants.IPC_Download_File, {
            Filename: name,
            URL: url,
          });
        }
      }
    };
    downloadAtIndex(0);
  };
};
