"use strict";

const {
  Template
} = require('webpack');

const plugInName = 'EFCResourceCleanup';
module.exports = class EfcResouceCleanupPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    compiler.hooks.thisCompilation.tap(plugInName, ({
      mainTemplate
    }) => {
      mainTemplate.hooks.afterStartup.tap(plugInName, source => {
        const {
          attributes,
          globalCacheObj
        } = this.options;
        const attributesArr = Object.entries(attributes);
        const [[attributekey, attributeValue]] = attributesArr;
        const resourceSelector = `[${attributekey}="${attributeValue}"]`;
        return Template.asString([source, Template.indent([`     window['${globalCacheObj}Jsonp'].unInstall = function() {
                  Object.keys(installedModules).forEach(installedModulesKey => installedModules[installedModulesKey] = null);
                  Object.keys(modules).forEach(moduleKey => modules[moduleKey] = null);
                 `, `
                 installedModules = null;
                 modules = null;
                 __webpack_require__.m = null;
                 __webpack_require__.c = null;
              
                 `, attributekey && attributeValue ? `    
          const addedResources = document.querySelectorAll('${resourceSelector}');
          addedResources.forEach(addedResource => addedResource.remove());
      }
          ` : ''])]);
      });
    });
  }

};