import { Plugin } from "..";
import * as fs from "fs";
import * as esbuild from "esbuild";

export default class TSCompiler extends Plugin {
  build: undefined;

  name = "ts-compiler";
  rewriteTriggers = ["ts", "tsx", "jsx"];
  renameTo = "js";
  longLasting = false;
  esbuildOptions: esbuild.BuildOptions;

  minify = false;

  constructor(minify: boolean, esbuildOptions: esbuild.BuildOptions = {}) {
    super();
    this.minify = minify;
    this.esbuildOptions = esbuildOptions;
  }
  
  async rewriteFile(file: string, filePath: string) {
    let result;
    try {
      result = await esbuild.build({
        stdin: {
          contents: file,
          resolveDir: filePath.split("/")?.slice(0, -1).join("/"),
          sourcefile: filePath.split("/").at(-1),
          loader: filePath.split("/").at(-1)?.split(".").at(-1) as
            | "ts"
            | "tsx"
            | "jsx",
        },
        jsxFragment: "Fragment",
        jsxFactory: "h",
        jsxImportSource: "preact",
        jsx: "transform",
        write: false,
        bundle: true,
        outdir: "out",
        minify: this.minify,
        ...this.esbuildOptions
      });
    } catch (e) {
      console.error(e);
      console.log("Errored!");
      return;
    }
    
    if (result.errors.length != 0) {
      console.log("TS compiler errored.");
      result.errors.forEach((element) => {
        console.error(element);
      });
    } else {
      const output = result.outputFiles![0].contents;
      return new TextDecoder().decode(output);
    }
  }
}
