import path from 'path';
import { loadConfig, tryLoadProjectConfig } from './config.js';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/** Experimental, allow dropping files from Unity into the running scene.
 * @param {"build" | "serve"} command
 * @param {import('../types/needleConfig').needleMeta | null | undefined} config
 * @param {import('../types/userconfig.js').userSettings} userSettings
 * @returns {import('vite').Plugin | null | undefined}
 */
export function needleDrop(command, config, userSettings) {
    if (command === "build") return;
    
    if(userSettings.useDrop !== true) return null;

    return {
        name: "needle:drop",
        config(/** @type {{ server?: { hmr?: { port?: number } } }} */ viteConfig) {
            if(userSettings)
            if (!viteConfig.server) viteConfig.server = {};
            if (!viteConfig.server.hmr) viteConfig.server.hmr = {};
            viteConfig.server.hmr.port = 8080;
            setTimeout(() => console.log("Update HMR port to " + viteConfig.server?.hmr?.port));
        },
        transformIndexHtml: {
            order: 'pre',
            handler(/** @type {string} */ html, /** @type {unknown} */ _) {
                const file = path.join(__dirname, 'drop-client.js');
                return [
                    {
                        tag: 'script',
                        attrs: {
                            type: 'module',
                        },
                        children: readFileSync(file, 'utf8'),
                        injectTo: 'body',
                    },
                ];
            },
        },
        configureServer(/** @type {{ ws: { on(event: string, cb: (...args: unknown[]) => void): void, send(type: string, data?: unknown): void } }} */ server) {

            server.ws.on('needle:drop-file', async (/** @type {unknown} */ data, /** @type {unknown} */ client) => {
                server.ws.send('needle-editor:drop-file', data);
            });
            // TODO: not sure how we can receive it with the normal vite server
            // server.ws.on("custom", (data, client) => {
            //     console.log(data);
            // })

            server.ws.on('connection', (/** @type {{ on(event: string, cb: (...args: unknown[]) => void): void }} */ socket, /** @type {unknown} */ request) => {
                socket.on('message', async (/** @type {Buffer | string} */ bytes) => {
                    try {
                        const message = Buffer.from(/** @type {ArrayBuffer} */ (bytes)).toString();
                        if (message && message.startsWith("{")) {
                            const obj = /** @type {{ type: string, data: unknown }} */ (JSON.parse(message));
                            if (obj.type === "needle-editor:exported-file") {
                                server.ws.send(obj.type, obj.data);
                            }
                        }
                    }
                    catch (/** @type {{ message?: string }} */ e) {
                        console.error(e.message);
                    }
                });
            });


            // setTimeout(() => {
            //     // console.log(server);
            //     console.log("WAIT FOR CON");
            //     server.ws.on('connection', (socket, request) => {
            //         console.log("FOUND CONNECTION");
            //         socket.on('message', (bytes) => {
            //             // console.log("FOUND MESSAGE");
            //             const message = Buffer.from(bytes).toString();
            //             console.log(message);
            //         });
            //     });
            //     setInterval(() => {
            //          server.ws.send({ type: 'editor', data: ["test", "123"] });
            //     }, 1000)
            // }, 1000)
        }
    }
}