const resolvePlugin = {
    name: "resolvePlugin",
    setup(build) {
        let path = require("path")
        // url in css does not resolve via esbuild-svelte correctly
        build.onResolve({ filter: /.*/, namespace: "fakecss" }, (args) => {
            // console.log(args)
            if (args.path.match(/^\./)) return { path: path.dirname(args.importer) + "/" + args.path }
            // return { path: path.join(args.resolveDir, "public", args.path) }
        })
    },
}

////////////////////////// esbuild-svelte

const sveltePlugin = require("esbuild-svelte")

const distDir = "frontend"

console.log("copy public dir...")
const copydir = require("copy-dir")
copydir.sync(__dirname + "/public", __dirname + "/" + distDir)
/*copydir.sync(
    __dirname + "/public/index.html",
    __dirname + "/" + distDir + "/template.html"
)*/

const svelteConfig = require("./svelte.config")
const esbuildSvelte = sveltePlugin({
    compilerOptions: {
        css: false,
        hydratable: true,
        dev: (process.argv?.length > 2 ? process.argv[2] : "build") !== "build",
    },
    preprocess: svelteConfig.preprocess,
    cache: true,
})

const options = {
    logLevel: "info",
    color: true,
    entryPoints: ["./src/index.ts"],
    outfile: "./" + distDir + "/_dist_/index.mjs",
    metafile: true, //"./" + distDir + "/_dist_/meta.json",
    format: "esm",
    minify: true,
    bundle: true,
    splitting: false,
    plugins: [esbuildSvelte, resolvePlugin],
    loader: {
        ".woff2": "file",
        ".woff": "file",
        ".eot": "file",
        ".svg": "file",
        ".ttf": "file",
        ".png": "file",
        ".jpg": "file",
    },
    sourcemap: true,
    target: ["es2020", "chrome61", "firefox60", "safari11", "edge18"],
}

const bsMiddleware = []

if (process.argv[2] == "start") {
    const { createProxyMiddleware } = require("http-proxy-middleware")
    const apiBase = process.env.API_BASE || "http://localhost:8080/api/v1/_/" + process.env.NAMESPACE
    bsMiddleware.push(
        createProxyMiddleware("/api", {
            target: apiBase,
            pathRewrite: { "^/api": "" },
            changeOrigin: true,
        })
    )
}

module.exports = {
    sveltePlugin: sveltePlugin,
    resolvePlugin: resolvePlugin,
    options: options,
    watch: {
        path: [__dirname + "/src/**/*"],
    },
    serve: {
        onRequest(args) {
            console.log(args)
        },
    },
    browserSync: {
        server: {
            baseDir: distDir,
            middleware: [
                require("morgan")("dev"),
                ...bsMiddleware,
                require("connect-history-api-fallback")({
                    index: "/spa.html",
                    // verbose: true,
                }),
            ],
        },
        open: false,
        // logLevel: "debug",
    },
}
