import React, { useState, useEffect, Fragment, useCallback, useRef } from 'react';
import { PropTypes } from 'prop-types';
import { useEEG } from 'eeg/EEG-Context';
import { connect } from 'react-redux';
import { useNotify } from 'notifications/Notify-Context';
import { timestampToDateString } from 'helpers/TimeUtils';
import useLoading from 'loading/use-loading';
import FileDropzone from 'form/dropzone/File-Dropzone';
import LinearProgress from '@material-ui/core/LinearProgress';
import useAlert from 'alerts/use-alert';
import UpgradeProgress from './Upgrade-Progress';

function RunUpgrade(props) {
  const dropzoneRef = useRef();

  const {
    upgradeStatusInterval,
    upgrade_progress: {
      error,
      error_message,
      progress,
      status,
      status_message,
    },
  } = props;
  const { setNotify } = useNotify();
  const { startLoading, stopLoading } = useLoading();
  const {
    initiateUpgradeProgressInterval,
    terminateUpgradeProgressInterval,
    resumeIntervals,
    pauseIntervals,
    loadState,
  } = useEEG();
  const [progressPercent, setProgressPercent] = useState(null);
  const { setAlert, hideAlert } = useAlert();
  const [showButton, setShowButton] = useState(false);

  const selectBz2 = 'Select a .tar.bz2 file for upload';

  const djsConfig = {
    addRemoveLinks: true,
    acceptedFiles: 'application/x-bzip2,.bz2',
    autoProcessQueue: false,
    chunkSize: 40000000,//10000,
    paramName: 'upgrade_file',
    dictDefaultMessage: selectBz2,
    maxFiles: 1,
    maxFilesize: 100000,
    createImageThumbnails: false,
    clickable: ['.ponies'],
  };
  // add to clickable for drop/drag on box: '.filepicker'

  const componentConfig = {
    iconFiletypes: ['.jpg', '.png', '.gif'],
    showFiletypeIcon: true,
    postUrl: '/system-webportal/upgrade',
  };

  useEffect(() => {
    // setNotify(status);
    if (error) {
      // console.log('terminate load license run upgrade alert use effect error');
      terminateUpgradeProgressInterval();
      resumeIntervals('run upgrade error');
      setAlert(error_message);
    } else if (progress >= 100) {
      hideAlert('submit run upgrade');
      stopLoading('run upgrade');
      if (upgradeStatusInterval) {
        setNotify('Completed Upgrade', { from: 'run upgrade' });
      }
      // console.log('terminate load license run upgrade alert use effect progress >= 100');
      terminateUpgradeProgressInterval();
      resumeIntervals('run upgrade success');
    }
  }, [error, error_message, progress, status, status_message]);

  function endUpload() {
    setProgressPercent(null);
    stopLoading();
    dropzoneRef.current.removeAllFiles();
  }

  function onAddedFile(file) {
    // console.log('added', file);
    setShowButton(true);
    // check maxSize, if already met, remove original file
    if (dropzoneRef.current.files.length > 1) {
      dropzoneRef.current.removeFile(dropzoneRef.current.files[0]);
      setShowButton(true);
    }
  }

  function onRemovedFile(file) {
    setShowButton(false);
    file.removed = true;
    // console.log('removed', file);
  }

  function onError(file, errorMsg) {
    let errorMessage = errorMsg;
    if (typeof errorMessage === 'string' && errorMessage.includes('DOCTYPE HTML PUBLIC')) {
      errorMessage = 'The upstream service encountered an error';
    }
    endUpload();
    setAlert(errorMessage);
    // TODO RemoveAllFiles
  }

  function onSuccess(file, response) {
    // console.log('onSuccess response', file, response);
    const successMessage = 'Uploaded Upgrade File';
    // console.log('success', successMessage, response);
    startLoading();
    initiateUpgradeProgressInterval(setAlert);
    setProgressPercent(100);
  }

  function onUploadProgress(file, uploadProgress) {
    // console.log('uploadProgress', uploadProgress);
    if (uploadProgress < 100) {
      setProgressPercent(uploadProgress);
    }
  }

  function onProcessing(file) {
    // console.log('processing', file);
  }

  function onSending(file, formData) {
    // console.log('sending', file, formData);
  }

  function onChunksUploaded(file, done) {
    // console.log('uploaded all chunks');
    done();
  }

  function onComplete(file) {
    // console.log('complete', file);
    endUpload();
  }

  function onCanceled(file) {
    // console.log('cancelled', file);
    endUpload();
  }

  const eventHandlers = {
    addedfile: onAddedFile,
    removedfile: onRemovedFile,
    error: onError,
    success: onSuccess,
    uploadprogress: onUploadProgress,
    chunksUploaded: onChunksUploaded,
    processing: onProcessing,
    sending: onSending,
    complete: onComplete,
    canceled: onCanceled,
  };

  return (
    <Fragment>
      <FileDropzone
        config={componentConfig}
        eventHandlers={eventHandlers}
        djsConfig={djsConfig}
        showUploadButton={showButton}
        ref={dropzoneRef}
      />
      {progressPercent !== null && (
        <LinearProgress variant="determinate" value={progressPercent} />
      )}
      <UpgradeProgress />
    </Fragment>
  );
}

RunUpgrade.propTypes = {
  upgrade_progress: PropTypes.object.isRequired,
  upgradeStatusInterval: PropTypes.object,
};


function mapStateToProps(state) {
  // console.log('run upgrade state', state);
  const {
    system: {
      upgrade: {
        upgrade_progress = {},
        statusInterval: upgradeStatusInterval,
      } = {},
    } = {},
  } = state;

  return { upgrade_progress, upgradeStatusInterval };
}

export default connect(mapStateToProps)(RunUpgrade);
