"use strict";

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

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

  _react = function _react() {
    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 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 _lodash() {
  const data = require("lodash");

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

  return data;
}

function _uppercamelcase() {
  const data = _interopRequireDefault(require("uppercamelcase"));

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

  return data;
}

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

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

  return data;
}

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

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

  return data;
}

function _rimraf() {
  const data = _interopRequireDefault(require("rimraf"));

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

  return data;
}

var _util = require("../util");

var _constants = require("../constants");

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var _default = (content, opts) => {
  const absolutePath = opts.absolutePath,
        isExtractBlock = opts.isExtractBlock,
        dontRemoveExtractedBlock = opts.dontRemoveExtractedBlock,
        relativePath = opts.relativePath,
        identifier = opts.identifier,
        _opts$index = opts.index,
        index = _opts$index === void 0 ? 0 : _opts$index,
        latest = opts.latest;

  function addImport(node, id) {
    const body = node.body;
    const lastImportSit = (0, _lodash().findLastIndex)(body, item => t().isImportDeclaration(item));
    const newImport = t().importDeclaration([t().importDefaultSpecifier(t().identifier(id))], t().stringLiteral(relativePath));
    body.splice(lastImportSit + 1, 0, newImport);
  }

  function getExtractBlockNode(stylesName) {
    const code = (0, _fs().readFileSync)(absolutePath, 'utf-8');
    const ast = (0, _util.parseContent)(code);
    let returnNode = null;
    let importNodes = [];
    (0, _traverse().default)(ast, {
      Program(path) {
        const node = path.node;
        let d = (0, _util.findExportDefaultDeclaration)(node);
        d = (0, _util.getIdentifierDeclaration)(d, path);
        const ret = (0, _util.getReturnNode)(d, path);
        returnNode = ret.node;
        importNodes = (0, _util.findImportNodes)(node);
      },

      Identifier(path) {
        const node = path.node;

        if (node.name === 'styles') {
          node.name = stylesName;
        }
      }

    });
    return {
      returnNode,
      importNodes
    };
  }

  function addBlockToJSX({
    newNode,
    node,
    replace,
    id
  }) {
    (0, _assert().default)((0, _util.isJSXElement)(node), 'add block to jsx failed, not valid jsx element'); // Build new node

    if (!newNode) {
      newNode = t().jsxElement(t().jsxOpeningElement(t().jsxIdentifier(id), [], true), null, [], true);
    }

    if ((0, _util.haveChildren)(node)) {
      // 是否最后插入
      if (latest) {
        node.children.push(newNode);
      } else {
        const insertIndex = (0, _util.findIndex)(node.children, index, _util.isJSXElement);
        node.children.splice(insertIndex, 0, newNode);
      }
    } else {
      replace(t().jsxFragment(t().jsxOpeningFragment(), t().jsxClosingFragment(), index === 0 ? [newNode, node] : [node, newNode]));
    }
  }

  const ast = (0, _util.parseContent)(content);

  if (typeof index === 'string' && index.startsWith(_constants.BLOCK_LAYOUT_PREFIX)) {
    const targetIndex = parseInt(index.replace(_constants.BLOCK_LAYOUT_PREFIX, ''), 10);
    let currIndex = 0;
    (0, _traverse().default)(ast, {
      // TODO: remove import { UmiUIFlag } from 'umi'
      // TODO: remove import { UmiUIFlag, AAA } from 'umi' => import { AAA } from 'umi'
      // ImportDeclaration: {
      //   exit(path) {
      //     const { node } = path;
      //     const specifierIndex = node.specifiers.findIndex(
      //       specify =>
      //         t.isImportSpecifier(specify) && specify.imported.name === UMI_UI_FLAG_PLACEHOLDER,
      //     );
      //     if (specifierIndex > -1) {
      //       if (node.specifiers.length === 1) {
      //         // import { UmiUIFlag } from 'umi'
      //         path.remove();
      //       } else {
      //         path.get(`specifiers.${specifierIndex}`).remove();
      //       }
      //     }
      //   },
      // },
      // support <UmiUIFlag inline={} />
      JSXElement(path) {
        const node = path.node;
        const openingElement = node.openingElement;

        if (t().isJSXIdentifier(openingElement.name) && openingElement.name.name === _constants.UMI_UI_FLAG_PLACEHOLDER) {
          if (targetIndex === currIndex) {
            // 添加过之后无需提示
            const id = (0, _uppercamelcase().default)(identifier);
            addImport(path.findParent(p => p.isProgram()).node, id);
            const newNode = t().jsxElement(t().jsxOpeningElement(t().jsxIdentifier(id), [], true), null, [], true);
            path.parent.children.push(newNode); // remove <UmiUIFlag />

            path.remove();
          }

          currIndex += 1;
        }
      },

      JSXText(path) {
        const node = path.node;
        const value = node.value;

        if (value.trim().startsWith(_constants.INSERT_BLOCK_PLACEHOLDER)) {
          if (targetIndex === currIndex) {
            // 添加过之后无需提示
            node.value = _constants.INSERT_BLOCK_PLACEHOLDER;
            const id = (0, _uppercamelcase().default)(identifier);
            addImport(path.findParent(p => p.isProgram()).node, id);
            const newNode = t().jsxElement(t().jsxOpeningElement(t().jsxIdentifier(id), [], true), null, [], true);
            path.parent.children.push(newNode);
          }

          currIndex += 1;
        }
      }

    });
  } else {
    (0, _traverse().default)(ast, {
      Program(path) {
        const node = path.node;
        let d = (0, _util.findExportDefaultDeclaration)(node); // support hoc

        while (t().isCallExpression(d)) {
          // eslint-disable-next-line
          d = d.arguments[0];
        }

        d = (0, _util.getIdentifierDeclaration)(d, path); // Support hoc again

        while (t().isCallExpression(d)) {
          // eslint-disable-next-line
          d = d.arguments[0];
        }

        const ret = (0, _util.getReturnNode)(d, path);
        (0, _assert().default)(ret, 'Can not find return node');
        const id = (0, _uppercamelcase().default)(identifier); // TODO: check id exists

        if (isExtractBlock) {
          const stylesName = (0, _util.getValidStylesName)(path);

          const _getExtractBlockNode = getExtractBlockNode(stylesName),
                returnNode = _getExtractBlockNode.returnNode,
                importNodes = _getExtractBlockNode.importNodes;

          const originImportNodes = (0, _util.findImportNodes)(node);
          (0, _util.combineImportNodes)(node, originImportNodes, importNodes, absolutePath, stylesName);
          addBlockToJSX(_objectSpread({}, ret, {
            id,
            newNode: returnNode
          })); // 清理目录

          if (!dontRemoveExtractedBlock) {
            _rimraf().default.sync(absolutePath);

            if ((0, _fs().readdirSync)((0, _path().dirname)(absolutePath)).length === 0) {
              _rimraf().default.sync((0, _path().dirname)(absolutePath));
            }
          }
        } else {
          addImport(node, id);
          addBlockToJSX(_objectSpread({}, ret, {
            id,
            newNode: null
          }));
        }
      }

    });
  } // console.log(JSON.stringify(ast, null, 2));


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

exports.default = _default;