import { Button } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import cleanAxios from "../../utils/CleanAxios";

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

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

export function JobsLocalGalleryDownloadButton({ bodyshop, galleryImages, allMedia, job }) {
  const { t } = useTranslation();
  const [download, setDownload] = useState(null);

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

  const handleDownload = async () => {
    const theDownloadedZip = await cleanAxios.post(
      `${bodyshop.localmediaserverhttp}/jobs/download`,
      {
        jobid: job.id,
        files: ((allMedia && allMedia[job.id]) || []).filter((i) => i.isSelected).map((i) => i.filename)
      },
      {
        headers: { ims_token: bodyshop.localmediatoken },
        responseType: "arraybuffer",
        onDownloadProgress: downloadProgress
      }
    );
    setDownload(null);
    standardMediaDownload(theDownloadedZip.data, job.ro_number);
  };

  return (
    <Button loading={!!download} onClick={handleDownload}>
      {t("documents.actions.download")}
    </Button>
  );
}

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