import { Button, Space } from "antd";
import axios from "axios";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import cleanAxios from "../../utils/CleanAxios";
import formatBytes from "../../utils/formatbytes";
//import yauzl from "yauzl";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobsDocumentsDownloadButton);

/*
################################################################################################
 Developer Note:
 Known Technical Debt Item
         Modifications to this code requires complementary changes to the Imgproxy code. This code will be removed once the imgproxy migration is completed.
################################################################################################
*/
export function JobsDocumentsDownloadButton({ bodyshop, galleryImages, identifier }) {
  const { t } = useTranslation();
  const [download, setDownload] = useState(null);

  const {
    treatments: { Direct_Media_Download }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Direct_Media_Download"],
    splitKey: bodyshop.imexshopid
  });

  const imagesToDownload = [
    ...galleryImages.images.filter((image) => image.isSelected),
    ...galleryImages.other.filter((image) => image.isSelected)
  ];

  function downloadProgress(progressEvent) {
    setDownload((currentDownloadState) => {
      return {
        downloaded: progressEvent.loaded || 0,
        speed: (progressEvent.loaded || 0) - ((currentDownloadState && currentDownloadState.downloaded) || 0)
      };
    });
  }

  const handleDownload = async () => {
    logImEXEvent("jobs_documents_download");

    const zipUrl = await axios({
      url: "/media/download",
      method: "POST",
      //responseType: "arraybuffer", // Important
      data: { ids: imagesToDownload.map((_) => _.key) }
    });

    const theDownloadedZip = await cleanAxios({
      url: zipUrl.data,
      method: "GET",
      responseType: "arraybuffer",
      onDownloadProgress: downloadProgress
    });
    setDownload(null);
    if (Direct_Media_Download.treatment === "on") {
      try {
        // const parentDir = await window.showDirectoryPicker({
        //   id: "media",
        //   startIn: "downloads",
        // });
        // const directory = await parentDir.getDirectoryHandle(identifier, {
        //   create: true,
        // });
        // yauzl.fromBuffer(
        //   Buffer.from(theDownloadedZip.data),
        //   {},
        //   (err, zipFile) => {
        //     if (err) throw err;
        //     zipFile.on("entry", (entry) => {
        //       zipFile.openReadStream(entry, async (readErr, readStream) => {
        //         if (readErr) {
        //           zipFile.close();
        //           throw readErr;
        //         }
        //         if (err) throw err;
        //         let fileSystemHandle = await directory.getFileHandle(
        //           entry.fileName,
        //           {
        //             create: true,
        //           }
        //         );
        //         const writable = await fileSystemHandle.createWritable();
        //         readStream.on("data", async function (chunk) {
        //           await writable.write(chunk);
        //         });
        //         readStream.on("end", async function () {
        //           await writable.close();
        //         });
        //       });
        //     });
        //   }
        // );
      } catch (e) {
        console.log(e);
        standardMediaDownload(theDownloadedZip.data);
      }
    } else {
      standardMediaDownload(theDownloadedZip.data);
    }

    function standardMediaDownload(bufferData) {
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(new Blob([bufferData]));
      a.href = url;
      a.download = `${identifier || "documents"}.zip`;
      a.click();
    }
  };

  return (
    <Button loading={!!download} disabled={imagesToDownload.length < 1} onClick={handleDownload}>
      <Space>
        <span>{t("documents.actions.download")}</span>
        {download && <span>{`(${formatBytes(download.downloaded)} @ ${formatBytes(download.speed)} / second)`}</span>}
      </Space>
    </Button>
  );
}
