const LibManifestPlugin = require('./LibManifestPlugin.js')
const FlagInitialModulesAsUsedPlugin = require('webpack/lib/FlagInitialModulesAsUsedPlugin')
const ExportWebpackRequireMainTemplatePlugin = require('./web/ExportWebpackRequireMainTemplatePlugin')

class RedevelopmentPlugin {
  constructor (options) {
    this.options = options
  }

  apply (compiler) {
    // compiler.hooks.entryOption.tap('RedevelopmentPlugin', (context, entry) => {
    //   const itemToPlugin = (item, name) => {
    //     if (!Array.isArray(item)) {
    //       item = [item]
    //     }
    //     return new RedevelopmentEntryPlugin(context, item, name)
    //     // throw new Error('RedevelopmentPlugin: supply an Array as entry')
    //   }
    //   if (typeof entry === 'object' && !Array.isArray(entry)) {
    //     Object.keys(entry).forEach(name => {
    //       itemToPlugin(entry[name], name).apply(compiler)
    //     })
    //   } else {
    //     itemToPlugin(entry, 'main').apply(compiler)
    //   }
    //   return true
    // })

    compiler.hooks.thisCompilation.tap('RedevelopmentReferencePlugin', (compilation, params) => {
      // 9 在这儿有chunks为空数组
      if (!this.options.name || typeof this.options.name === 'object') {
        this.options.name = 'reference_for_redevelopment'
      }
      // new SetVarMainTemplatePlugin(`var ${this.options.name}`, false).apply(compilation)
      // 不要上面这些弯弯绕绕了，直接设置一个全局变量指向 __webpack_require__ 吧
      new ExportWebpackRequireMainTemplatePlugin(this.options).apply(compilation.mainTemplate);

    })

    new LibManifestPlugin(this.options).apply(compiler)
    if (!this.options.entryOnly) {
      new FlagInitialModulesAsUsedPlugin('RedevelopmentPlugin').apply(compiler)
    }
  }
}

module.exports = RedevelopmentPlugin
