import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js';
import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts";
import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts";
import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2";
import * as Twind from "https://esm.sh/@twind/core@1.1.3";
import React from "react";
import * as Iso from "@eno/iso";

let hosted = import.meta.resolve("./");
const Path = {
    Hosted:hosted.substring(0, hosted.length-1),
    Active:`file://${Deno.cwd().replaceAll("\\", "/")}`
};
console.log(Path);

const Transpiled = new Map();
const Transpileable =(inFilePath:string):boolean=>
{
    let dotIndex = inFilePath.length-4;
    if(inFilePath[dotIndex] !== ".")
    {
        if(inFilePath[++dotIndex] !== ".")
        {
            return false;
        }
    }

    if(inFilePath[dotIndex+2] == "s")
    {
        const first = inFilePath[dotIndex+1];
        return (first == "t" || first == "j");
    }

    return false;
};
const Transpile =async(inCode:string, inKey:string):Promise<string>=>
{
    const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap: "inline", minify:true });
    Transpiled.set(inKey, transpile.code);
    return transpile.code;
};
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
{
    if(inCheck)
    {
        const cached = Transpiled.get(inKey);
        if(cached)
        {
            return cached;
        }
    }
    let body = await fetch(inPath);
    let text = await body.text();
    return Transpile(text, inKey);
};


const LibPath = "lib";
type ImportMap = {imports?:Record<string, string>, importMap?:string};
let ImportObject:ImportMap = {};
try
{
    const confDeno = await fetch(`${Path.Active}/deno.json`);
    const confDenoParsed:ImportMap = await confDeno.json();
    if(confDenoParsed.importMap)
    {
        try
        {
            const confImports = await Deno.readTextFile(confDenoParsed.importMap);
            try
            {
                ImportObject = JSON.parse(confImports);
            }
            catch(e)
            {
                console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
            }
        }
        catch(e)
        {
            console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
        }
    }
    else if(confDenoParsed.imports)
    {
        ImportObject = {imports:confDenoParsed.imports};
    }

    if(ImportObject.imports)
    {
        const importReact = ImportObject.imports["react"];
        if(importReact)
        {
            ImportObject.imports["react-original"] = importReact;
            ImportObject.imports["react"] = `/${LibPath}/react.tsx`;
        }
        else
        {
            console.log(`"imports" configuration does not alias "react"`);
        }

        const importApp = ImportObject.imports["@eno/app"];
        if(importApp)
        {
            
        }
        else
        {
            console.log(`"imports" configuration does not alias an entry-point component with "@eno/app"`);
        }
        
        const importIso = ImportObject.imports["@eno/iso"];
        if(importIso)
        {
            ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`;
        }
        else
        {

        }
        Object.entries(ImportObject.imports).forEach(([key, value])=>{
            if(value.startsWith("./") && ImportObject.imports)
            {
                ImportObject.imports[key] = value.substring(1);
            }
        })
    }
    else
    {
        console.log(`No "imports" found in configuration`);
    }
}
catch(e)
{
    console.log(`deno.json not found`);
}


Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
{
    const url:URL = new URL(_req.url);
    const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/");
    const pathLast = pathParts.at(-1);
    const pathExt:string|undefined = pathLast?.split(".")[1];

    console.log(pathParts, pathLast, pathExt);

    console.log(`Request for "${url.pathname}"...`);    

    if(_req.headers.get("upgrade") == "websocket")
    {
        try
        {
          const { response, socket } = Deno.upgradeWebSocket(_req);
          socket.onopen = () =>
          {
              Sockets.add(socket);
              console.log("Overwatch: Socket created");
          };
          socket.onclose = () =>
          {
              Sockets.delete(socket);
              console.log("Overwatch: Socket deleted");
          };
          socket.onmessage = (e) => {};
          socket.onerror = (e) => console.log("Overwatch: Socket errored:", e);
          return response;
        }
        catch(e)
        {
            //
        }
    }

    try
    {
        // serve index by default
        let type = `text/html`;
        let body:BodyInit = ``;

        const isLib = url.pathname.startsWith(`/${LibPath}/`);

        if(Transpileable(pathLast))
        {
            type = `application/javascript`;
            if(isLib)
            {
                body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
            }
            else if(!url.searchParams.get("reload"))
            {
                const imp = await import(Path.Active+url.pathname);
                const members = [];
                for( const key in imp ) { members.push(key); }
                body =
`
import {FileListen} from "/${LibPath}/hmr.tsx";
import * as Import from "${url.pathname}?reload=0";
${ members.map(m=>`let proxy_${m} = Import.${m};
export { proxy_${m} as ${m} };
`).join(" ") }
const reloadHandler = (updatedModule)=>
{
    ${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
};
FileListen("${url.pathname}", reloadHandler);`;

            }
            else
            {
                body = await TranspileURL(Path.Active+url.pathname, url.pathname, true);
            }
        }
        // serve static media
        else if( pathExt )
        {
            type = MIME.typeByExtension(pathExt) || "text/html";
            const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname);
            body = await _fetch.text();
        }
        else
        {
            const results = Twind.extract(SSR(<Iso.Router.Provider url={url}><App/></Iso.Router.Provider>), TwindInst);

            type = `text/html`;
            body = `<!doctype html>
<html lang="en">
    <head>
        <title>${Iso.Meta.title}</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8"/>
        <style data-twind>${results.css}</style>
        <script type="importmap">${JSON.stringify(ImportObject)}</script>
        <script async src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js" crossorigin="anonymous"></script>
    </head>
    <body>
        <div id="app">${results.html}</div>
        <script type="module">
            import {render, createElement as H} from "react";
            import * as Twind from "https://esm.sh/@twind/core@1.1.3";
            import {default as App, CSS} from "@eno/app";
            import {Router} from "@eno/iso";
            Twind.install(CSS);
            render( H(Router.Provider, null, H(App)), document.querySelector("#app"));
        </script>
    </body>
</html>`;
        }

        return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
    }
    catch(error)
    {
        console.log(error);
        return new Response(error, {status:404});
    }
});

import App, {CSS} from "@eno/app";
const TwindInst = Twind.install(CSS);

const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }

const FilesChanged:Map<string, string> = new Map();
const ProcessFiles =debounce(async()=>
{
    console.log("Processing Files...", FilesChanged);
    for await (const [path, action] of FilesChanged)
    {
        const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
        console.log(key, action);

        if(action != "remove")
        {
            await TranspileURL(Path.Active+key, key, false);
            console.log(`  ...cached "${key}"`);
            SocketsBroadcast(key);
        }
        else
        {
            Transpiled.delete(key);
        }
    }
    FilesChanged.clear();
}, 1000);
for await (const event of Deno.watchFs(Deno.cwd()))
{
    event.paths.forEach( path =>
    {
        if(Transpileable(path))
        {
            FilesChanged.set(path, event.kind);
        }
    });
    if(FilesChanged.size)
    {
        ProcessFiles();
    }
}