import { FileOneView } from "./FileOneView";
import React, { useState } from "react";
import {
  MdDownload,
  MdOutlineDelete,
} from "react-icons/md";

import FileInput from "./FileInput";
import { FileViewInput } from "../types";
import { ChangingArrow } from "./ChangingArrow";
export function FileView({
  generateFile,
  grammar,
  getFile,
  fileToGrammar,
  deleteFile,
  deleteFilesFromGrammar,
}: FileViewInput) {
  const [xml, setXml] = useState(false);
  const [more, setMore] = useState(false);
  const [fileInput, setFileInput] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [text, setText] = useState("");
  const [saveGenFile, setSaveGenFile] = useState(false);
  const fileAdd = (
    file: string,
    xml: boolean | null,
    save: boolean,
    diff: boolean
  ) => {
    fileToGrammar(file, xml, grammar.id, save, diff);
  };
  return (
    <>
      <p>
        <button onClick={() => setXml(!xml)}>{xml ? "JSGF" : "XML"}</button>{" "}
        <input
          id="gensave"
          type="checkbox"
          defaultChecked={saveGenFile}
          onClick={() => setSaveGenFile(!saveGenFile)}
        ></input>
        <label className="smallText" htmlFor="gensave">
          save
        </label>{" "}
        <button onClick={() => generateFile(xml, grammar.id, saveGenFile)}>
          GENERATE {xml ? "XML" : "JSGF"}{" "}
        </button>{" "}
        <a
          href={
            (window.location.hostname === "localhost"
              ? "http://localhost:8080"
              : "") +
            "/api/files/grammar/" +
            grammar.id +
            "/generated?format=" +
            (xml ? "xml" : "jsgf") +
            "&download=true"
          }
        >
          <MdDownload />
        </a>{" "}
      </p>
      {(xml ? grammar.xmlGen : grammar.jsgfGen) && (
        <p>
          <textarea
            className="transparent big"
            readOnly={true}
            rows={15}
            cols={50}
            value={xml ? grammar.xmlGen : grammar.jsgfGen}
          />
        </p>
      )}
      <button onClick={() => setFileInput(!fileInput)}>
        {fileInput ? "CANCEL" : "ADD FILE"}
      </button>
      {"  "}
      {fileInput && (
        <FileInput
          fileAdd={fileAdd}
          file={file}
          setFile={setFile}
          setText={setText}
          text={text}
          newDiff={true}
        />
      )}
      <div className="cell">{grammar.files.length + " files"}</div>
      <MdOutlineDelete onClick={() => deleteFilesFromGrammar(grammar.id)} />
      <ChangingArrow   more={more} setMore={setMore}  />

      {more && (
        <div className="table">
          {grammar.files.map((file) => (
            <FileOneView
              key={file.id}
              file={file}
              getFile={getFile}
              deleteFile={deleteFile}
              grammar={grammar}
            />
          ))}
        </div>
      )}
    </>
  );
}
