"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;
exports.update = update;

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _fs() {
  const data = require("fs");

  _fs = function _fs() {
    return data;
  };

  return data;
}

function parser() {
  const data = _interopRequireWildcard(require("@babel/parser"));

  parser = function parser() {
    return data;
  };

  return data;
}

function _traverse() {
  const data = _interopRequireDefault(require("@babel/traverse"));

  _traverse = function _traverse() {
    return data;
  };

  return data;
}

function _generator() {
  const data = _interopRequireDefault(require("@babel/generator"));

  _generator = function _generator() {
    return data;
  };

  return data;
}

function _template() {
  const data = _interopRequireDefault(require("@babel/template"));

  _template = function _template() {
    return data;
  };

  return data;
}

function t() {
  const data = _interopRequireWildcard(require("@babel/types"));

  t = function t() {
    return data;
  };

  return data;
}

function _assert() {
  const data = _interopRequireDefault(require("assert"));

  _assert = function _assert() {
    return data;
  };

  return data;
}

function _prettier() {
  const data = _interopRequireDefault(require("prettier"));

  _prettier = function _prettier() {
    return data;
  };

  return data;
}

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }

function _default({
  key,
  value,
  file,
  plugin
}) {
  let content = `export default {}`;

  if ((0, _fs().existsSync)(file)) {
    content = (0, _fs().readFileSync)(file, 'utf-8');
  }

  const newContent = update(content, key, value, plugin);
  (0, _fs().writeFileSync)(file, `${newContent}\n`, 'utf-8');
}

function buildExpression(keys, str) {
  if (str.startsWith('{') || str.startsWith('[')) {// do nothing
  } else if (str === 'true' || str === 'false') {// do nothing
  } else {
    str = `'${str}'`;
  }

  let exp = (0, _template().default)(`(${str})`, {
    placeholderPattern: false
  })().expression;
  let i = 0;
  keys = keys.reverse();

  while (i < keys.length) {
    exp = t().objectExpression([t().objectProperty(t().identifier(keys[i]), exp)]);
    i += 1;
  }

  return exp;
}

function getVariableDeclarator(node, path) {
  if (t().isIdentifier(node) && path.scope.hasBinding(node.name)) {
    const bindingNode = path.scope.getBinding(node.name).path.node;

    if (t().isVariableDeclarator(bindingNode)) {
      node = bindingNode.init;
    }
  }

  return node;
}

function findPluginConfig(node, path, plugin) {
  let plugins = node.properties.find(p => {
    return t().isIdentifier(p.key) && p.key.name === 'plugins';
  }).value;
  (0, _assert().default)(plugins, `plugins is not configured.`);
  plugins = getVariableDeclarator(plugins, path);
  (0, _assert().default)(t().isArrayExpression(plugins), `plugins must be array.`);

  var _iterator = _createForOfIteratorHelper(plugins.elements.entries()),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      let _step$value = _slicedToArray(_step.value, 2),
          index = _step$value[0],
          el = _step$value[1];

      if (t().isStringLiteral(el) && el.value === plugin) {
        el = (0, _template().default)(`(['${plugin}', {}])`)().expression;
        plugins.elements.splice(index, 1, el);
      }

      el = getVariableDeclarator(el, path);

      if (t().isArrayExpression(el) && t().isStringLiteral(el.elements[0]) && el.elements[0].value === plugin) {
        if (!el.elements[1]) {
          el.elements.push((0, _template().default)(`({})`)().expression);
        }

        let config = el.elements[1];
        config = getVariableDeclarator(config, path);
        (0, _assert().default)(t().isObjectExpression(config), `config for ${plugin} is not object`);
        return config;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
}

function update(content, key, value, plugin) {
  const ast = parser().parse(content, {
    sourceType: 'module',
    plugins: ['jsx', 'typescript']
  });
  (0, _traverse().default)(ast, {
    ExportDefaultDeclaration(path) {
      let node = path.node.declaration; // export default {} as IConfig;

      if (node.type === 'TSAsExpression') {
        node = node.expression;
      } // const a;
      // export default a;


      node = getVariableDeclarator(node, path);
      (0, _assert().default)(t().isObjectExpression(node), `config file must export default a Plain Object`);

      if (plugin) {
        node = findPluginConfig(node, path, plugin);
      }

      let _node = node,
          properties = _node.properties;
      let obj = key;

      if (typeof key === 'string') {
        obj = {
          [key]: value
        };
      }

      Object.keys(obj).forEach(key => {
        const value = obj[key];
        const keys = key.split('.');
        let i = 0;
        let ps = properties;

        while (i < keys.length) {
          let hasFound;

          var _iterator2 = _createForOfIteratorHelper(ps),
              _step2;

          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              const property = _step2.value;

              if (t().isIdentifier(property.key, {
                name: keys[i]
              })) {
                if (i === keys.length - 1 || !t().isObjectExpression(property.value)) {
                  property.value = buildExpression(keys.slice(i + 1), value);
                  return;
                } else {
                  ps = property.value.properties;
                }

                hasFound = true;
                break;
              }
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }

          if (!hasFound) {
            ps.push(t().objectProperty(t().identifier(keys[i]), buildExpression(keys.slice(i + 1), value)));
            break;
          } else {
            i += 1;
          }
        }
      });
    }

  });
  const newCode = (0, _generator().default)(ast, {}).code;
  return _prettier().default.format(newCode, {
    singleQuote: true,
    trailingComma: 'es5',
    printWidth: 100,
    parser: 'typescript'
  });
}