import { FunctionComponent } from "preact";
import { Content } from "../../components/Content.tsx";
import { SERVER_STATE } from "../../state/serverState.ts";
import { FileUploader } from "../../islands/fileUploader.tsx";

export default async function ModsFolder() {
  const files: string[] = [];
  if (
    SERVER_STATE.serverType !== "unset" && SERVER_STATE.serverType !== "vanilla"
  ) {
    for await (const fileEntry of Deno.readDir("./server/mods")) {
      if (fileEntry.isFile) {
        files.push(fileEntry.name);
      }
    }
  }

  return (
    <div className="container p-8">
      <Content>
        <h2 class="font-pixel text-xl">Active Mods</h2>
        <FileUploader path="./server/mods">
          <div className="relative grid lg:grid-cols-3 min-h-[100px]">
            {!files.length && (
              <div class="absolute place-self-center">Drop files here to upload</div>
            )}
            {files.map((f) => (
              <div class="flex gap-2 items-center">
                <FileIcon fileName={f} />
                {f}
              </div>
            ))}
          </div>
        </FileUploader>
      </Content>
    </div>
  );
}

const FileIcon: FunctionComponent<{ fileName: string }> = ({ fileName }) => {
  let icon;
  switch (fileName.split(".")[1]) {
    case "jar":
      icon = "fa-brand fa-java";
      break;
    case "tmp":
    case "temp":
      icon = "fas fa-ghost";
      break;
    case "png":
    case "jpg":
    case "jpeg":
    case "webp":
      icon = "fas fa-image";
      break;
    default:
      icon = "fas fa-file";
  }

  return <i class={icon}></i>;
};
