import React, { useCallback } from "react";
import { MdOutlineSave } from "react-icons/md";
import { useEffect, useState } from "react";
import { FileInputInput } from "../types";

const FileInput = ({
  fileAdd,
  file,
  setFile,
  setText,
  text,
  newDiff,
}: FileInputInput) => {
  const getText = useCallback(
    async (file: File | null) => {
      if (file === null || file.name === null) {
        setText("");
        return;
      }
      let ending = getEnding(file);
      if (!(ending === "jsgf" || ending === "xml")) {
        setText("invalid file type");
        return;
      }
      if (file.size > 32 * 1028 * 1028) {
        setText("file too large to be seen");
        return;
      }
      let textPro = await file.text();
      setText(textPro);
    },
    [setText]
  );
  const [save, setSave] = useState(true);
  const [diff, setDiff] = useState(false);
  useEffect(() => {
    getText(file);
  }, [file, getText]);

  function getEnding(file: File) {
    let splited = file.name.split(".");
    return splited[splited.length - 1];
  }

  const handleFileSubmit = async () => {
    if (file == null) {
      if (text == null) {
        return;
      }
      fileAdd(text, null, save, diff);
      return;
    }
    let changeText = text;
    if (text === "file too large to be seen") {
      changeText = await file.text();
    }
    let ending = getEnding(file);
    let xml = false;
    switch (ending) {
      case "xml":
        xml = true;
        break;
      case "grxml":
        xml = true;
        break;
      case "jsgf":
        xml = false;
        break;
      default:
        alert("unknown file type");
        return;
    }
    fileAdd(changeText, xml, save, diff);
  };
  const changeFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files == null) {
      setFile(null);
      return;
    }
    setFile(e.target.files[0]);
  };

  return (
    <form onSubmit={handleFileSubmit} className="fileInput">
      <p>
        <input
          type="checkbox"
          defaultChecked={save}
          onClick={() => setSave(!save)}
          id="save"
        />
        <label htmlFor="save" className="smallText">
          save
        </label>{" "}
        {newDiff && (
          <>
            <input
              type="checkbox"
              defaultChecked={diff}
              onClick={() => setDiff(!diff)}
              id="newDiff"
            />
            <label htmlFor="newDiff" className="smallText">
              add new grammar on diff
            </label>{" "}
          </>
        )}
        <input type="file" onChange={changeFileInput} />
        <MdOutlineSave onClick={handleFileSubmit} />
      </p>
      <textarea
        className="transparent big"
        onChange={(e) => setText(e.target.value)}
        rows={15}
        cols={15}
        value={text}
      />
    </form>
  );
};

export default FileInput;
