import React from "react";
import { useState } from "react";
import { MdDownload, MdRefresh, MdOutlineDelete } from "react-icons/md";
import { FileOneViewInput } from "../types";
import { ChangingArrow } from "./ChangingArrow";
export const FileOneView = ({
  file,
  getFile,
  deleteFile,
  grammar,
}: FileOneViewInput) => {
  const [more, setMore] = useState(true);
  const calculateFileSize = (size: number) => {
    if (size < 1024) {
      return size.toString() + " B";
    }
    if (size < 1024 * 1024) {
      return (size / 1024).toFixed(3).toString() + " kB";
    }
    if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(3).toString() + " MB";
    }
    return (size / (1024 * 1024 * 1024)).toFixed(3).toString() + " GB";
  };
  return (
    <div className="cell" key={file.id}>
      <table>
        <thead>
          <tr>
            <th>Generated</th>
            <th>Xml</th>
            <th>Size</th>
            <th>
              {file.size > 32 * 1028 * 1028 || (
                <MdRefresh
                  onClick={() => {
                    setMore(true);
                    getFile(file.id, grammar.id);
                  }}
                />
              )}
            </th>
            <th rowSpan={2}>
              <a
                href={
                  //test production difference
                  (window.location.hostname === "localhost"
                    ? "http://localhost:8080"
                    : "") +
                  "/api/files/" +
                  +file.id +
                  "?download=true"
                }
              >
                <MdDownload />
              </a>
            </th>
            <th rowSpan={2}>
              <MdOutlineDelete
                onClick={() => deleteFile(file.id, grammar.id)}
              />
            </th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{file.generated ? "✓" : "❌"}</td>
            <td>{file.xml ? "✓" : "❌"}</td>
            <td>{calculateFileSize(file.size)}</td>
            {file.content && (
              <td>
                <ChangingArrow more={more} setMore={setMore} />
              </td>
            )}
          </tr>
          <tr>
            <td colSpan={5}>
              {file.content && more && (
                <textarea
                  className="transparent big"
                  readOnly={true}
                  rows={15}
                  cols={50}
                  value={file.content}
                />
              )}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};
