import React from "react";
import { getTranslation } from "../core/i18n/I18NHandler";
import { getSensorLog } from "../core/log/SensorLogger";
import { Button } from "@geist-ui/core";
import { getUserID } from "./RandomIDComponent";
import { PARTICIPANT_NUMBER } from "../core/Constants";

function DownloadButton() {
  const downloadFile = ({ data, fileName, fileType }) => {
    const blob = new Blob([data], { type: fileType });
    const a = document.createElement("a");
    a.download = fileName;
    a.href = window.URL.createObjectURL(blob);
    const clickEvt = new MouseEvent("click", {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    a.dispatchEvent(clickEvt);
    a.remove();
  };

  const userData = {
    participantId: getUserID(),
    sensorLog: getSensorLog(),
    participantNumber: PARTICIPANT_NUMBER,
  };

  const exportToJson = (e) => {
    e.preventDefault();
    downloadFile({
      data: JSON.stringify(userData),
      fileName: "sensorData.json",
      fileType: "text/json",
    });
  };

  return <Button onClick={exportToJson}>{getTranslation("download")}</Button>;
}

export default DownloadButton;
