import find from 'lodash/find';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import React, { useContext, useEffect } from 'react';
import { usePrevious } from '../../../hooks/usePrevious';
import { AttachmentDispatchContext, AttachmentStateContext } from './AttachmentReducerContext';
import FileLister from './FileLister';
import { IFileLocal, onFileEdit, onFileRemove } from './reducer/AttachemntReducer';
import { uploadAllFiles, uploadFile } from './reducer/AttachmentHelper';

interface IProps {
    caseNumber?: string;
}
const defaultProps: Partial<IProps> = {};

export default function FileUploader(props: IProps) {
    const caseNumber = props.caseNumber;
    const prevCaseNumber = usePrevious(caseNumber);
    const { attachmentState } = useContext(AttachmentStateContext);
    const dispatchToAttachmentReducer = useContext(AttachmentDispatchContext);
    const isUploadingAttachment = !isEmpty(find(attachmentState.caseFiles.selectedLocalFiles, (localFile) => localFile.uploadProgress.inProgress || localFile.uploadProgress.verifying));

    const onRetryLocal = (indexToRetry: number) => {
        if (props.caseNumber && attachmentState.caseFiles.selectedLocalFiles[indexToRetry]) {
            uploadFile(dispatchToAttachmentReducer,
                props.caseNumber,
                attachmentState.caseFiles.selectedLocalFiles[indexToRetry],
                attachmentState.caseFiles.selectedOriginalFiles[indexToRetry],
                indexToRetry);
        }
    };
    const onFileEditLocal = async (editedLocalFile: IFileLocal, fileIndexToEdit: number) => {
        onFileEdit(dispatchToAttachmentReducer, editedLocalFile, fileIndexToEdit);
    };
    const onFileRemoveLocal = async (fileIndexToRemove: number) => {
        onFileRemove(dispatchToAttachmentReducer, fileIndexToRemove);
    };
    const onUploadAll = () => {
        uploadAllFiles(dispatchToAttachmentReducer, props.caseNumber, attachmentState.caseFiles);
    };
    useEffect(() => {
        if (caseNumber && caseNumber !== '' && (!prevCaseNumber || prevCaseNumber === '')) {
            onUploadAll();
        }
    }, [caseNumber]);

    return (<section className="push-top">
        {isUploadingAttachment &&  <h3>Please wait. Files are uploading...</h3>}
        {get(attachmentState.caseFiles, 'selectedLocalFiles.length', 0) > 0 && (
            <FileLister
                selectedLocalFiles={attachmentState.caseFiles.selectedLocalFiles}
                onFileEdit={onFileEditLocal}
                onFileRemove={onFileRemoveLocal}
                onRetry={onRetryLocal}
            />
        )}
    </section>);
}
FileUploader.defaultProps = defaultProps;
