const path = require("path");

let mocks = {
  fs: require.resolve(path.join(__dirname, "../mock/fs")),
  net: require.resolve(path.join(__dirname, "../mock/net")),
  os: require.resolve(path.join(__dirname, "../mock/os")),
  child_process: require.resolve(path.join(__dirname, "../mock/child_process")),
  process: require.resolve(path.join(__dirname, "../mock/process")),

  stream: require.resolve("readable-stream"),
  util: require.resolve("util/util.js"),
  assert: require.resolve("assert"),
  path: require.resolve("path-browserify"),
  timers: require.resolve("timers-browserify"),
  crypto: require.resolve("crypto-browserify"),
}

function fixProcessModule(compiler) {
  new webpack.ProvidePlugin({
    "process": path.resolve(path.join(__dirname, '../mock/process')),
  }).apply(compiler);
  new webpack.DefinePlugin({
    "process.env": '(globalThis.__nstd_env__||{})',
  }).apply(compiler)
}

const webpack = require("webpack");

let AliasPlugin
try {
  AliasPlugin = require("enhanced-resolve/lib/AliasPlugin")
} catch (e){
  AliasPlugin = require("webpack/node_modules/enhanced-resolve/lib/AliasPlugin")
}

module.exports = class NodeSourcePlugin {
  constructor(options) {
    this.options = options;
  }
  apply(compiler) {
    fixProcessModule(compiler)

    compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => {
      for (const lib of Object.keys(mocks)) {
	compiler.resolverFactory.hooks.resolver
	  .for("normal")
	  .tap("NodeSourcePlugin", resolver => {
	    new AliasPlugin(
	      "described-resolve",
	      {
		name: lib,
		onlyModule: true,
		alias: mocks[lib],
	      },
	      "resolve"
	    ).apply(resolver);
	  });
      }
    });
  }
};
