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

export default function JobsDocumentsDownloadButton({
  galleryImages,
  identifier,
}) {
  const { t } = useTranslation();
  const [download, setDownload] = useState(null);
  const imagesToDownload = [
    ...galleryImages.images.filter((image) => image.isSelected),
    ...galleryImages.other.filter((image) => image.isSelected),
  ];
  const handleDownload = () => {
    logImEXEvent("jobs_documents_download");

    axios
      .post("/media/download", {
        ids: imagesToDownload.map((_) => _.key),
      })
      .then((r) => {
        //     window.open(r.data);
        downloadAs(
          r.data,
          `${identifier || "images"}.zip`,
          (progressEvent) => {
            const percentage = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            console.log(progressEvent, percentage);
            setDownload((currentDownloadState) => {
              return {
                downloaded: progressEvent.loaded || 0,
                speed:
                  (progressEvent.loaded || 0) -
                  ((currentDownloadState && currentDownloadState.downloaded) ||
                    0),
              };
            });
          },
          () => setDownload(null)
        );
      });
  };

  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>
    </>
  );
}

const downloadAs = (url, name, onDownloadProgress, onCompleted) => {
  cleanAxios
    .get(url, {
      headers: {
        "Content-Type": "application/octet-stream",
      },
      responseType: "blob",
      onDownloadProgress: onDownloadProgress,
    })
    .then((response) => {
      onCompleted && onCompleted();
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(response.data);
      a.href = url;
      a.download = name;
      a.click();
    })
    .catch((err) => {
      console.log("error", err);
    });
};
