import * as ESBuild from 'https://deno.land/x/esbuild@v0.17.4/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 { parse as JSONC} from "https://deno.land/std@0.185.0/jsonc/mod.ts";
import { toFileUrl } from "https://deno.land/std@0.185.0/path/mod.ts";
import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2";
import Prepass from "https://esm.sh/preact-ssr-prepass@1.2.0";
import * as Twind from "https://esm.sh/@twind/core@1.1.3";
import React from "react";
import * as Iso from "@eno/iso";

/**
 * Setup a transpiler.
 * @param inDevMode When true, starts a file-watcher
 * @returns 
 */
function Transpiler(inDevMode:boolean)
{
    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, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, sourcefile:inKey} :
        {  loader: "tsx",
        minify:true,
        jsx:"automatic",
        jsxImportSource:"https://esm.sh/preact@10.13.2"});
    
        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 Sockets:Set<WebSocket> = new Set();
    const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
    const SocketsHandler = inDevMode ? (_req:Request)=>
    {
        if(_req.headers.get("upgrade") == "websocket")
        {
            try
            {
              const { response, socket } = Deno.upgradeWebSocket(_req);
              socket.onopen = () => Sockets.add(socket);
              socket.onclose = () => Sockets.delete(socket);
              socket.onmessage = (e) => {};
              socket.onerror = (e) => console.log("Socket errored:", e);
              return response;
            }
            catch(e)
            {
                //
            }
        }
        return false;
    }
    :
    ()=>false;

    const watcher =async()=>
    {
        const FilesChanged:Map<string, string> = new Map();
        const ProcessFiles =debounce(async()=>
        {
            for await (const [path, action] of FilesChanged)
            {
                const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
                if(action != "remove")
                {
                    await TranspileURL(Path.Active+key, key, false);
                    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();
            }
        }
    }

    if(inDevMode)
    {
        watcher().then(()=>{console.log("done watching");});
    }

    return {TranspileURL, Transpileable, SocketsHandler};

}

type ImportMap = {imports?:Record<string, string>, importMap?:string};
/**
 * Extract all configuration info form a project's deno.jsonc file
 * @param inDevMode When true, proxies react to an HMR-enabled version
 * @param inLibPath 
 * @returns 
 */
async function Configure(inDevMode:boolean, inLibPath:string)
{
    const output:{Imports?:ImportMap, Error?:string} = {};
    let ImportObject:ImportMap = {};
    try
    {
        const confDeno = await fetch(`${Path.Active}/deno.jsonc`);
        const confText = await confDeno.text();
        const confDenoParsed = JSONC(confText) as ImportMap;
        if(confDenoParsed.importMap)
        {
            try
            {
                const confImports = await Deno.readTextFile(confDenoParsed.importMap);
                try
                {
                    output.Imports = JSON.parse(confImports);
                }
                catch(e)
                {
                    output.Error = `"importMap" "${confDenoParsed.importMap}" contains invalid JSON`;
                    return output;
                }
            }
            catch(e)
            {
                output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`;
                return output;
            }
        }
        else if(confDenoParsed.imports)
        {
            output.Imports  = {imports:confDenoParsed.imports};
        }
    
        if(output.Imports?.imports)
        {
            if(inDevMode)
            {
                const importReact = output.Imports.imports["react"];
                if(importReact)
                {
                    output.Imports.imports["react-original"] = importReact;
                    output.Imports.imports["react"] = `/${inLibPath}/react.tsx`;
                }
                else
                {
                    output.Error = `"imports" configuration does not alias "react"`;
                    return output;
                }
            }
    
            const importIso = output.Imports.imports["@eno/iso"];
            if(importIso)
            {
                output.Imports.imports["@eno/iso"] = `/${inLibPath}/iso.tsx`;
            }
            else
            {
                output.Error = `"imports" configuration does not alias "@eno/iso"`;
                return output;
            }
    
    
            Object.entries(output.Imports.imports).forEach(([key, value])=>{
                if(value.startsWith("./") && output.Imports?.imports)
                {
                    output.Imports.imports[key] = value.substring(1);
                }
            })
        }
        else
        {
            output.Error = `No "imports" found in configuration`;
            return output;
        }
    }
    catch(e)
    {
        output.Error = `error during configuration: ${e}`;
        return output;
    }
    return output;
}

Deno.args.forEach(arg=>
{
    if(arg.startsWith("--"))
    {
        const kvp = arg.substring(2).split("=");
        Deno.env.set(kvp[0], kvp[1] ? kvp[1] : "true");
    }
});

let DevMode = Deno.env.get("dev") ? true : false;
let hosted = import.meta.resolve("./");
const Path = {
    Hosted: hosted.substring(0, hosted.length-1),
    Active: `file://${Deno.cwd().replaceAll("\\", "/")}`,
    LibDir: "lib",
    AppDir: ""
};
console.log(Path);
console.log(`Dev Mode: ${DevMode}`);
console.log(`import.meta.url:`, import.meta.url);
console.log(`Deno.cwd():`, Deno.cwd());
console.log(`Deno.mainModule:`, Deno.mainModule);


let Booted = false;
let TwindInst:Twind.Twind;
export function Boot(inApp:React.FunctionComponent, inCSS?:object)
{
    if(Booted){return;}
    Booted = true;

    const pathInit = Deno.mainModule;
    const pathProj = toFileUrl(Deno.cwd());
    
    //@ts-ignore
    TwindInst = Twind.install({...Iso.CSS, ...inCSS||{}});

    const App = inApp;
    Path.AppDir = pathInit.split(pathProj.toString())[1];

    Server(App, Path.AppDir, TwindInst);
}

async function Server(App:React.FunctionComponent, AppPath:string, TwindInst:Twind.Twind)
{
    const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode);
    const {Imports, Error} = await Configure(DevMode, Path.LibDir);
    if(Error)
    {
        console.log(Error);
    }
    else if(App && TwindInst)
    {
        Deno.serve({ port: Deno.env.get("port")||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];
            
            const resp = SocketsHandler(_req);
            if(resp){ return resp; }
        
            console.log(url.pathname);

            try
            {
                // serve index by default
                let type = `text/html`;
                let body:BodyInit = ``;
        
                const isLib = url.pathname.startsWith(`/${Path.LibDir}/`);
        
                if(Transpileable(url.pathname))
                {
                    type = `application/javascript`;
                    if(isLib)
                    {
                        body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
                    }
                    else if(url.pathname == "/server.tsx")
                    {
                        body = await TranspileURL(`${Path.Hosted}/${Path.LibDir}/boot-client.tsx`, url.pathname, true);
                    }
                    else if(DevMode && !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 "/${Path.LibDir}/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((Path.Active)+url.pathname);
                    body = await _fetch.text();
                }
                else
                {
                    Iso.Fetch.ServerBlocking = [];
                    Iso.Fetch.ServerTouched = new Set();
                    Iso.Fetch.ServerRemove = new Set();
                    let app = <Iso.Router.Provider url={url}><Iso.Meta.Provider><App/></Iso.Meta.Provider></Iso.Router.Provider>;
                    await Prepass(app)
                    let bake = SSR(app);
                    while(Iso.Fetch.ServerBlocking.length)
                    {
                        await Promise.all(Iso.Fetch.ServerBlocking);
                        Iso.Fetch.ServerBlocking = [];
                        // at this point, anything that was requested that was not cached, has now been loaded and cached
                        // this next render will use cached resources. using a cached resource (if its "Seed" is true) adds it to the "touched" set.
                        app = <Iso.Router.Provider url={url}><Iso.Meta.Provider><App/></Iso.Meta.Provider></Iso.Router.Provider>;
                        await Prepass(app)
                        bake = SSR(app);
                    }
        
                    const seed:Iso.FetchRecord[] = [];
                    Iso.Fetch.ServerTouched.forEach((record)=>{
                        const r:Iso.FetchRecord = {...record};
                        delete r.Promise;
                        seed.push(r);
                    });
                    Iso.Fetch.ServerTouched = false;
        
                    const results = Twind.extract(bake, TwindInst);
        
                    type = `text/html`;
                    body =
        `<!doctype html>
        <html lang="en">
            <head>
                <title>${Iso.Meta.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(Imports)}</script>
            </head>
            <body>
                <div id="app">${results.html}</div>
                <script type="module">
                    import {Fetch} from "@eno/iso";
                    Fetch.Seed(${JSON.stringify(seed)});

                    import "${AppPath}";
                </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});
            }
        });
    }
}
