import React, { Component } from "react";
import Dropzone from "../dropzone/Dropzone";
import "./Upload.css";
import Progress from "../progress/Progress";
import CheckCircle from '../../assets/images/check_circle.svg';
import Config from '../../../../config/appConstants';

class Upload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      files: [],
      uploading: false,
      uploadProgress: {},
      successfullUploaded: false
    };
    this.onFilesAdded = this.onFilesAdded.bind(this);
    this.uploadFiles = this.uploadFiles.bind(this);
    this.sendRequest = this.sendRequest.bind(this);
    this.renderActions = this.renderActions.bind(this);
  }

  onFilesAdded(files) {
    this.setState(prevState => ({
      files: prevState.files.concat(files)
    }));
  }

  async uploadFiles() {
    this.setState({
      uploadProgress: {},
      uploading: true
    });
    const promises = [];
    this.state.files.forEach(file => {
      promises.push(this.sendRequest(file));
    });

    try {
      await Promise.all(promises);
      this.setState({
        successfullUploaded: true,
        uploading: false
      });
    } catch (e) {
      // Not Production ready! Do some error handling here instead...
      this.setState({
        successfullUploaded: true,
        uploading: false
      });
    }
  }

  sendRequest(file) {
    return new Promise((resolve, reject) => {
      const req = new XMLHttpRequest();
      req.upload.addEventListener("progress", event => {
        if (event.lengthComputable) {
          const copy = { ...this.state.uploadProgress
          };
          copy[file.name] = {
            state: "pending",
            percentage: event.loaded / event.total * 100
          };
          this.setState({
            uploadProgress: copy
          });
        }
      });
      req.upload.addEventListener("load", event => {
        const copy = { ...this.state.uploadProgress
        };
        copy[file.name] = {
          state: "done",
          percentage: 100
        };
        this.setState({
          uploadProgress: copy
        });
        resolve(req.response);
      });
      req.upload.addEventListener("error", event => {
        const copy = { ...this.state.uploadProgress
        };
        copy[file.name] = {
          state: "error",
          percentage: 0
        };
        this.setState({
          uploadProgress: copy
        });
        reject(req.response);
      });
      const formData = new FormData();
      formData.append("file", file, file.name);
      req.open("POST", `${Config.FILE_UPLOAD}`);
      req.send(formData);
    });
  }

  renderProgress(file) {
    var name = this.props.name;
    console.log("@#@!", name, file);
    var object = {};
    object["name"] = name;
    object["filename"] = file.name;
    this.props.files.push(object);
    console.log(this.props.files, "^^^", name);
    const uploadProgress = this.state.uploadProgress[file.name];

    if (this.state.uploading || this.state.successfullUploaded) {
      return /*#__PURE__*/React.createElement("div", {
        className: "ProgressWrapper"
      }, /*#__PURE__*/React.createElement(Progress, {
        progress: uploadProgress ? uploadProgress.percentage : 0
      }), /*#__PURE__*/React.createElement("img", {
        className: "CheckIcon",
        alt: "done",
        src: CheckCircle,
        style: {
          opacity: uploadProgress && uploadProgress.state === "done" ? 0.5 : 0
        }
      }));
    }
  }

  renderActions() {
    if (this.state.successfullUploaded) {
      return /*#__PURE__*/React.createElement("button", {
        onClick: () => this.setState({
          files: [],
          successfullUploaded: false
        })
      }, "Clear");
    } else {
      return /*#__PURE__*/React.createElement("button", {
        disabled: this.state.files.length < 0 || this.state.uploading,
        onClick: this.uploadFiles
      }, "Upload");
    }
  }

  render() {
    return /*#__PURE__*/React.createElement("div", {
      className: "maincontainer"
    }, /*#__PURE__*/React.createElement("div", {
      className: "container form-list sample-field"
    }), /*#__PURE__*/React.createElement("div", {
      className: "rowDiv"
    }, /*#__PURE__*/React.createElement("div", {
      className: "col-md-12"
    }, /*#__PURE__*/React.createElement("div", {
      className: "table-responsive-xl table-hover mh-table"
    }, /*#__PURE__*/React.createElement("table", {
      className: "table"
    }, /*#__PURE__*/React.createElement("thead", null, /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "S.No."), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "Document Type"), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "Upload"), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "File Name"), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "Status"), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "Preview"), /*#__PURE__*/React.createElement("th", {
      scope: "col"
    }, "Delete"))), /*#__PURE__*/React.createElement("tbody", null, /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("td", null, "1."), /*#__PURE__*/React.createElement("td", null, "Krooki Certificate"), /*#__PURE__*/React.createElement("td", null, /*#__PURE__*/React.createElement("input", {
      id: "fileInput",
      type: "file"
    })), /*#__PURE__*/React.createElement("td", null, /*#__PURE__*/React.createElement("button", {
      type: "button"
    }, "Upload")), /*#__PURE__*/React.createElement("td", null, "Krooki-Certificate.pdf"))))))));
  }

}

export default Upload;