/**
 * Load less-variables into a JS object.
 *
 * Based on https://github.com/atroo/less-to-json-loader, which has been patched to be made work.
 */
/* eslint-disable */
const less = require('less');
const loaderUtils = require('loader-utils');

const convertToCamelcase = (input) =>
  input.toLowerCase().replace(/-(.)/g, (match, group) => group.toUpperCase());

module.exports = function (source) {
  const query = loaderUtils.parseQuery(this.query);
  const prefix = query.ignoreWithPrefix || null;
  const path = query.path || [];

  const callback = this.async();
  this.cacheable && this.cacheable();

  const lessVars = {};
  const config = {
    paths: path,
    javascriptEnabled: true,
  };

  if (query.sourceMap) {
    config.sourceMap = {
      outputSourceFiles: true,
    };
  }

  less.parse(source, config, (err, root, imports, options) => {
    if (err) {
      return callback(err);
    }

    try {
      const evalEnv = new less.contexts.Eval(options);
      const evaldRoot = root.eval(evalEnv);
      const ruleset = evaldRoot.rules;
      ruleset.forEach((rule) => {
        if (rule.variable === true) {
          const name = convertToCamelcase(rule.name.substr(1));

          if (!prefix || name.substr(0, prefix.length) !== prefix) {
            const { value } = rule;
            lessVars[name] = value.toCSS(options);
          }
        }
      });
    } catch (e) {
      return callback(e);
    }
    callback(null, `module.exports = ${JSON.stringify(lessVars)}`);
  });
};
