import FolderOpenIcon from "@mui/icons-material/FolderOpen";
import IosShareIcon from "@mui/icons-material/IosShare";
import { IconButton, Tooltip } from "@mui/material";
import { useAlert } from "../hooks/providers/AlertDialogProvider";

export function ConfigImportExportButtons(p: {
  filename: string;
  currentConf: any;
  importConf?: (content: any) => any;
}): React.ReactElement {
  const alert = useAlert();

  const exportConf = () => {
    const conf = JSON.stringify(p.currentConf);
    const blob = new Blob([conf], { type: "application/json" });

    const a = document.createElement("a");
    a.href = window.URL.createObjectURL(blob);
    a.download = p.filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  const importConf = async () => {
    try {
      // Create file element
      const fileEl = document.createElement("input");
      fileEl.type = "file";
      fileEl.accept = "application/json";
      fileEl.click();

      // Wait for a file to be chosen
      await new Promise((res, _rej) =>
        fileEl.addEventListener("change", () => res(null))
      );

      if ((fileEl.files?.length ?? 0) === 0) return null;

      // Import conf
      let file = fileEl.files![0];
      const content = await file.text();
      p.importConf?.(JSON.parse(content));
    } catch (e) {
      console.error(e);
      alert(`Failed to load config from file!\n${e}`);
    }
  };

  return (
    <>
      <Tooltip title={"Export current config"}>
        <IconButton
          onClick={exportConf}
          size="small"
          style={{ paddingBottom: "0px", paddingTop: "0px" }}
        >
          <IosShareIcon />
        </IconButton>
      </Tooltip>
      {p.importConf && (
        <Tooltip title={"Import config from file"}>
          <IconButton
            onClick={importConf}
            size="small"
            style={{ paddingBottom: "0px", paddingTop: "0px" }}
          >
            <FolderOpenIcon />
          </IconButton>
        </Tooltip>
      )}
    </>
  );
}
