import { IComponents } from './WpjConfig';
import Handlebars from 'handlebars';

let components: IComponents = {};
var loaderUtils = require('loader-utils');
const fs = require('fs');

module.exports = {
   default: function (content, map, meta) {
      var params = loaderUtils.parseQuery(this.resourceQuery);

      const template_data = [];

      for (const [name, component] of Object.entries(components)) {
         if (!component.entrypoints.includes(params.entrypoint)) {
            continue;
         }

         if (!component.version_js && !component.version_css) {
            continue;
         }

         const template_component = {
            name: name,
            ...component,
            file_js: component.version_js ? component.template.replace(/\.(\d+)\.html\.twig/, `.${component.version_js}`) : null,
            file_css: component.version_css ? component.template.replace(/\.(\d+)\.html\.twig/, `.${component.version_css}.scss`) : null,
            lazy: params.entrypoint === 'lazy',
         };

         template_data.push(template_component);
      }

      const result = [];

      const components_js = Handlebars.compile(fs.readFileSync(__dirname + '/components.hbs', 'utf8'));
      result.push(components_js({components: template_data.filter(value => value.lazy === false)}));

      const components_lazy = Handlebars.compile(fs.readFileSync(__dirname + '/components_lazy.hbs', 'utf8'));
      result.push(components_lazy({components: template_data.filter(value => value.lazy === true)}));

      return result.join("\n\n");
   },
   setComponents: function(config) {
      components = config;
   }
}
