import * as Constants from '../../constants';
import {createAction} from 'redux-starter-kit';
import {getIPCRenderer} from '../../utils';

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, url, completedCallback) => {
  return (dispatch, getState) => {
    const state = getState();
    if (!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);
          ipcRenderer.removeListener(Constants.IPC_Download_File_Complete, downloadFileComplete);
          completedCallback(name, type, url, arg.data);
          dispatch(setDownloadEnd(arg.data));
        };

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

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