"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findExportDefaultDeclaration = findExportDefaultDeclaration;
exports.findImportNodes = findImportNodes;
exports.getValidStylesName = getValidStylesName;
exports.combineImportNodes = combineImportNodes;
exports.getIdentifierDeclaration = getIdentifierDeclaration;
exports.isReactCreateElement = isReactCreateElement;
exports.isJSXElement = isJSXElement;
exports.haveChildren = haveChildren;
exports.isChildFunc = isChildFunc;
exports.getReturnNode = getReturnNode;
exports.findIndex = findIndex;
exports.parseContent = parseContent;

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

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

  return data;
}

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

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

  return data;
}

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

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

  return data;
}

function _path() {
  const data = require("path");

  _path = function _path() {
    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 findExportDefaultDeclaration(programNode) {
  var _iterator = _createForOfIteratorHelper(programNode.body),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      const n = _step.value;

      if (t().isExportDefaultDeclaration(n)) {
        return n.declaration;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
}

function findImportNodes(programNode) {
  return programNode.body.filter(n => {
    return t().isImportDeclaration(n);
  });
}

function findImportWithSource(importNodes, source) {
  var _iterator2 = _createForOfIteratorHelper(importNodes),
      _step2;

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

      if (importNode.source.value === source) {
        return importNode;
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
}

function findSpecifier(importNode, specifier) {
  var _iterator3 = _createForOfIteratorHelper(importNode.specifiers),
      _step3;

  try {
    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      const s = _step3.value;
      if (t().isImportDefaultSpecifier(specifier) && t().isImportDefaultSpecifier(s)) return true;

      if (specifier.imported.name === s.imported.name) {
        if (specifier.local.name === s.local.name) return true;
        throw new Error('specifier conflicts');
      }
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }

  return false;
}

function combineSpecifiers(newImportNode, originImportNode) {
  newImportNode.specifiers.forEach(specifier => {
    if (!findSpecifier(originImportNode, specifier)) {
      originImportNode.specifiers.push(specifier);
    }
  });
}

function getValidStylesName(path) {
  let name = 'styles';
  let count = 1;

  while (path.scope.hasBinding(name)) {
    name = `styles${count}`;
    count += 1;
  }

  return name;
}

function combineImportNodes(programNode, originImportNodes, newImportNodes, absolutePath, stylesName) {
  newImportNodes.forEach(newImportNode => {
    // replace stylesName
    // TODO: 自动生成新的 name，不仅仅是 styles
    if (stylesName !== 'styles' && newImportNode.source.value.charAt(0) === '.') {
      newImportNode.specifiers.forEach(specifier => {
        if (t().isImportDefaultSpecifier(specifier) && specifier.local.name === 'styles') {
          specifier.local.name = stylesName;
        }
      });
    }

    const importSource = newImportNode.source.value;

    if (importSource.charAt(0) === '.') {
      // /a/b/c.js -> b
      const dir = (0, _path().basename)((0, _path().join)(absolutePath, '..'));
      newImportNode.source = t().stringLiteral(`./${(0, _path().join)(dir, importSource)}`);
    }

    const originImportNode = findImportWithSource(originImportNodes, newImportNode.source.value);

    if (!originImportNode) {
      programNode.body.unshift(newImportNode);
    } else {
      combineSpecifiers(newImportNode, originImportNode);
    }
  });
}

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

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

    return bindingNode;
  }

  return node;
}

function isReactCreateElement(node) {
  return t().isCallExpression(node) && t().isMemberExpression(node.callee) && t().isIdentifier(node.callee.object, {
    name: 'React'
  }) && t().isIdentifier(node.callee.property, {
    name: 'createElement'
  });
}

function isJSXElement(node) {
  return t().isJSXElement(node) || t().isJSXFragment(node) || isReactCreateElement(node);
}

function haveChildren(node) {
  if (t().isJSXElement(node) || t().isJSXFragment(node)) {
    return node.children && node.children.length;
  } else {
    return !!node.arguments[2];
  }
}
/**
 * React child function
 * <Bar>
 *  {foo => <div />}
 * </Bar>
 *
 * or
 * React.createElement(Media, { query: "(max-width: 599px)" }, isMobile => {} })
 * @param node
 */


function isChildFunc(node) {
  return t().isJSXElement(node) && node.children.some(child => t().isJSXExpressionContainer(child)) || isReactCreateElement(node) && node.arguments.some(arg => t().isArrowFunctionExpression(arg));
}

function getReturnNode(node, path) {
  if (t().isArrowFunctionExpression(node) || t().isFunctionDeclaration(node) || t().isFunctionExpression(node)) {
    return findReturnNode(node, path);
  } else if (t().isClassDeclaration(node) || t().isClassExpression(node)) {
    const renderStatement = findRenderStatement(node.body);

    if (renderStatement) {
      return findReturnNode(renderStatement, path);
    }
  }
}

function findReturnNode(node, path) {
  if (isJSXElement(node.body)) {
    return {
      node: node.body,

      replace(newNode) {
        node.body = newNode;
      }

    };
  }

  if (t().isBlockStatement(node.body)) {
    var _iterator4 = _createForOfIteratorHelper(node.body.body),
        _step4;

    try {
      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
        const n = _step4.value;

        if (t().isReturnStatement(n)) {
          return {
            node: n.argument,

            replace(newNode) {
              n.argument = newNode;
            }

          };
        }
      }
    } catch (err) {
      _iterator4.e(err);
    } finally {
      _iterator4.f();
    }
  } // if (t.isConditionalExpression(node.body)) {
  //   return getReturnNode({
  //     body: getIdentifierDeclaration(node.body.consequent, path),
  //   }, path);
  // }
  // throw new Error(`Find return statement failed, unsupported node type ${node.body.type}.`);

}

function findRenderStatement(node) {
  var _iterator5 = _createForOfIteratorHelper(node.body),
      _step5;

  try {
    for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
      const n = _step5.value;

      if (t().isClassMethod(n) && t().isIdentifier(n.key) && n.key.name === 'render') {
        return n;
      }
    } // throw new Error(`Find render statement failed`);

  } catch (err) {
    _iterator5.e(err);
  } finally {
    _iterator5.f();
  }
}

function findIndex(arr, index, fn) {
  if (index === 0) return 0;
  let foundCount = 0;

  var _iterator6 = _createForOfIteratorHelper(arr.entries()),
      _step6;

  try {
    for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
      const _step6$value = _slicedToArray(_step6.value, 2),
            i = _step6$value[0],
            item = _step6$value[1];

      if (fn(item)) {
        foundCount += 1;
      }

      if (foundCount === index) {
        return i + 1;
      }
    }
  } catch (err) {
    _iterator6.e(err);
  } finally {
    _iterator6.f();
  }

  throw new Error(`Invalid find index params.`);
}

function parseContent(code) {
  return parser().parse(code, {
    sourceType: 'module',
    plugins: ['jsx', 'decorators-legacy', 'typescript', 'classProperties', 'dynamicImport']
  });
}