import { useTracker, useSubscribe, useFind } from 'meteor/react-meteor-data/suspense';
import { Meteor } from 'meteor/meteor';
import React, { useState, useRef, Suspense } from 'react';
// import PropTypes from 'prop-types';
import { FilesCol } from '/imports/api/files.js';

import IndividualFilePOI from '/imports/ui/files/IndividualFilePOI.jsx'; // <-------------------------

import _ from 'lodash';

//const debug = require('debug')('demo:file');

const useFiles = () => {
  useSubscribe('files.all');

  const files = useTracker("files", () => FilesCol.find({}).fetchAsync(), []);

  return files;
};



const ShowUploads = ({uploading, progress, filePreviewURI, inProgress}) => {
  // console.log('**********************************', uploading);

  if (!_.isEmpty(uploading)) {
    // console.log("uploading: ", uploading);
    return inProgress && <div style={{
      border: `1px solid`,
      borderRadius: `5px`,
      color: `#cccc`,
      padding: `1rem`,
      marginBottom: `1em`
    }}>
      {uploading.file.name}

      <img src={filePreviewURI} />
      <div className="progress progress-bar-default">
        <div style={{width: progress + '%'}} aria-valuemax="100"
          aria-valuemin="0"
          aria-valuenow={progress || 0} role="progressbar"
          className="progress-bar"
        >
          <span className="sr-only">{progress}% Complete (success)</span>
          <span>{progress}%</span>
        </div>
      </div>
    </div>;
  }
};


const DisplayUploadFile = ({files}) => files?.map(async (aFile, key) => {
        
  let link = await FilesCol.findOneAsync({_id: aFile._id});  //The "view/download" link
  let linkOriginalURL = `${window.location.origin}${link._fileRef._downloadRoute}/${link._fileRef._collectionName}/${link._fileRef._id}/original/${link._fileRef._id}.${link._fileRef.extension}`;

  // Send out components that show details of each file

  return <div key={'file' + key}>
      <IndividualFilePOI
        fileName={aFile.name}
        fileUrl={linkOriginalURL}
        fileId={aFile._id}
        fileSize={aFile.size}
      />
    </div>;
}).reverse();


const FileUploadPOI = (props) => {
  
  const [uploading, setUploading] = useState([]);
  const [progress, setProgress] = useState(0);
  const [inProgress, setInProgress] = useState(false);

  const [filePreviewURI, setFilePreviewURI] = useState(null);

  const fileinput = useRef();

  const files = useFiles();

  console.log("files: ", files);
  // console.log("fileinput: ", fileinput);

  function uploadIt(e) {
    e.preventDefault();
    
    console.log("UPLOADING IT");

    if (e.currentTarget.files && e.currentTarget.files[0]) {
      // We upload only one file, in case
      // there was multiple files selected
      var file = e.currentTarget.files[0];
  
      console.log("E: ", e);
      console.log("FILE: ", file);

      if (file) {
  
        let reader = new FileReader();

        console.log("READER: ", reader);

        // reader.onload = (evt) => {
        //   console.log("ONLOAD: ", evt.target.result);
        // };
        reader.readAsDataURL(e.currentTarget.files[0]);

        reader.onload = function(ev){
          

          console.log("ev.target.result: ", ev.target.result);

          setFilePreviewURI(ev.target.result);

          console.log("filePreviewURI: ", filePreviewURI);

  
          let uploadInstance = FilesCol.insert({
            file,
            meta: {
              locator: props.fileLocator,
              userId: props.uidProvisional || Meteor.userId(), // Optional, used to check on server for file tampering
              entId: props.entId
            },
            chunkSize: 'dynamic',
            allowWebWorkers: true // If you see issues with uploads, change this to false
          }, false)
  
          setUploading(uploadInstance); // Keep track of this instance to use below
          console.log("setInProgress: true");
          setInProgress(true); // Show the progress bar now
          
          // These are the event functions, don't need most of them, it shows where we are in the process
          uploadInstance.on('start', function () {
            console.log('Starting');
            console.log("file: ", file);
          })
  
          uploadInstance.on('End', function (error, fileObj) {
            console.log('On end File Object: ', fileObj);
            setProgress(0);
            console.log("setInProgress: false");
            setInProgress(false);
          })
  
          uploadInstance.on('uploaded', function (error, fileObj) {
            console.log('uploaded: ', fileObj);
  
        //    props.setUpId(fileObj._id);
  
            // Remove the filename from the upload box
            fileinput.current.value = '';
  
            // Reset our state for the next file
            setUploading([]);
            setProgress(0);
            console.log("setInProgress: false");
            setInProgress(false);
          })
  
          uploadInstance.on('error', function (error, fileObj) {
            console.log('Error during upload: ' + error)
            console.log("setInProgress: false");
            setInProgress(false);
          });
  
          uploadInstance.on('progress', function (progress, fileObj) {
            console.log('Upload Percentage: ' + progress)
            // Update our progress bar
            setProgress(progress);
            if (progress === 100) {
              console.log("setInProgress: false");
              setInProgress(false);
            }
          });
  
          uploadInstance.start(); // Must manually start the upload
        }
      }
    }
  }


  return <>

    <button
      className='btArxiu'
      onClick={ev => {
        ev.preventDefault();
        ev.stopPropagation();

        // refForm.current.reset();
        fileinput.current.click();
        //reseter[1](reseter[0] + 1);
        //refForm.current.reset();
        // ev.target.value = null;
      }}
    >
      <span className="fa-solid fa-image" >Add file</span>
    </button>

    <input type="file"
      id="fileinput"
      disabled={inProgress}
      ref={fileinput}
      onChange={() => {
        setInProgress(true);
      }}
      style={{display: `none`}}
      name="fileinput"
      onClick={(ev) => {
        // ev.preventDefault();
        ev.stopPropagation();
      }}
    />

    <br /><br />

    <div className="row m-t-sm m-b-sm">
      <div className="col-md-6">

        <ShowUploads progress={progress} filePreviewURI={filePreviewURI} uploading={uploading} inProgress={inProgress} />

      </div>
    </div>

    <DisplayUploadFile files={files} />

  </>;
    // else return <div>Carregant llista d'arxius...</div>;
};

export default FileUploadPOI;