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 (
        <div className="ProgressWrapper">
          <Progress progress={uploadProgress ? uploadProgress.percentage : 0} />
          <img
            className="CheckIcon"
            alt="done"
            src={CheckCircle}
            style={{
              opacity:
                uploadProgress && uploadProgress.state === "done" ? 0.5 : 0
            }}
          />
        </div>
      );
    }
  }

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

  render() {
    return (
      <div className="maincontainer">
      <div className="container form-list sample-field"></div>
      <div className="rowDiv">
      <div className="col-md-12">
          <div className="table-responsive-xl table-hover mh-table">
              <table className="table">
                <thead>
                  <tr>
                    <th scope="col">S.No.</th>
                    <th scope="col">Document Type</th>
                    <th scope="col">Upload</th>
                    <th scope="col"></th>
                    <th scope="col">File Name</th>
                    <th scope="col">Status</th>
                    <th scope="col">Preview</th>
                    <th scope="col">Delete</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>1.</td>
                    <td>Krooki Certificate</td>
                    <td><input id="fileInput" type="file"/></td>
                    <td><button type="button">Upload</button></td>
                    <td>Krooki-Certificate.pdf</td>
                    {/* <td><a href="#"><img src={Complete} alt="complete" /></a></td>
                    <td><a href="#"><img src={FileImage} alt="preview" /></a></td>
                    <td><a href="#"><img src={Delete} alt="delete" /></a></td> */}
                  </tr>
                </tbody>
              </table>
            </div>
      </div>
    </div>
    </div>
    );
  }
}

export default Upload;
