import * as esbuild from 'esbuild';

import babel from 'esbuild-plugin-babel';
import { sassPlugin } from 'esbuild-sass-plugin';
import svgPlugin from 'esbuild-plugin-svg-bundle';
// import svgPlugin from 'esbuild-plugin-svg';
import { copy } from 'esbuild-plugin-copy';
// import manifestPlugin from 'esbuild-plugin-manifest';
import manifestPlugin from 'esbuild-plugin-assets-manifest';
// import copyWithHashPlugin from '@enonic/esbuild-plugin-copy-with-hash';
// import inlineImportPlugin from 'esbuild-plugin-inline-import';
import { nodeModulesPolyfillPlugin } from 'esbuild-plugins-node-modules-polyfill';

const staticDir = './static';
const wellKnownDir = './well-known';
const wellKnownDirs = [ `${wellKnownDir}/de-de-formal`, `${wellKnownDir}/en-eu` ];

await esbuild.build({
  bundle: true,
  minify: true,
  sourcemap: true,
  entryPoints: {
    main: './frontend/src/main.js',
    polyfill: './frontend/src/polyfill.js',
  },
  outdir: staticDir,
  plugins: [
    /* inlineImportPlugin({
      filter: /.svg/,
    }), */
    svgPlugin({
      minify: true,
      // hash: 'foo', // TODO: introduce caching of static files (maybe even in backend)
      bundleFile: 'svg-bundle.svg',
      bundleUrl: 'svg-bundle.svg',
    }),
    nodeModulesPolyfillPlugin({
      // modules: ['crypto','worker_threads']
    }),
    sassPlugin(),
    copy({
      resolveFrom: 'cwd',
      assets: {
        from: [ './assets/favicons/*' ],
        to: wellKnownDirs,
      },
    }),
    copy({
      resolveFrom: 'cwd',
      assets: {
        from: [ './config/robots.txt' ],
        to: wellKnownDirs,
      },
    }),
    // ...['de-de-formal','en-eu'].map((lang) => manifestPlugin({
    manifestPlugin({
      filename: 'manifest.json',
      path: 'config',
      // metadata: { timestamp: new Date(), module: 'myapp', type: 'esm', },
      processOutput(assets) {
        const orderAssets = {
          main: assets['main'],
          ...assets
        };
        return JSON.stringify(orderAssets, null, '  ');
      },
    }),
    /* copyWithHashPlugin({
      patterns: [
        './assets/favicons/*',
        './config/robots.txt',
      ],
    }), */
    babel({
      config: {
        "sourceMaps": "inline",
        "presets": [
          "@babel/preset-env",
        ],
        "plugins": [
          ["@babel/plugin-proposal-decorators", { "legacy": true }],
          ["@babel/plugin-syntax-dynamic-import"],
          ["@babel/plugin-transform-class-properties", { "loose": true }],
          ["@babel/plugin-transform-private-methods", { "loose": true }],
          ["@babel/plugin-transform-private-property-in-object", { "loose": true }],
          ["@babel/plugin-transform-modules-commonjs"],
          ["@babel/transform-runtime"],
          ["@babel/plugin-syntax-jsx"],
        ],
      },
    }),
  ],
});