import { Handlers, PageProps } from "$fresh/server.ts";
import ListPackageDetails from "../islands/ListPackageDetails.tsx";
import { handler as fetchPackages  } from "./api/npm.ts";

export const handler: Handlers<any> = {
  async POST(req, ctx) {
    const form = await req.formData();
    const fileData = form.get("packagefile") as File;
    const packagejson = await parsePackageJson(fileData);
    const packages = {...packagejson.dependencies, ...packagejson.devDependencies};
    const {name, version, description} = packagejson
    return ctx.render({packages, name, version, description});
  },
};

const parsePackageJson = (fileData: File) => {
  return new Promise<any>((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsText(fileData);
    reader.addEventListener("load", (event: any) => {
      resolve(JSON.parse(reader.result as string));
    });
  });
};

export default function Analyze({ data }: PageProps<any>) {
    const {packages, name, version, description} = data;
  return (
    <div>
      Analyzer
      <ListPackageDetails 
        packages={packages} 
        projectname={name} 
        projectversion={version}
        projectdesc={description}
      ></ListPackageDetails>
    </div>
  );
}
