const fs = require('fs');
const path = require('path');
const t = require('@babel/types');
const { parse } = require('@babel/parser');

const originCode = fs.readFileSync(
  path.join(__dirname, '../src/router/index.js'),
  'utf-8',
);
const originAST = parse(originCode, { sourceType: 'module' });
const expDefNode = originAST.program.body.find((node) =>
  t.isExportDefaultDeclaration(node),
);
const rootNode = expDefNode.declaration.elements[0];
const pagesNodeArr = rootNode.properties.find(
  (node) => node.key && node.key.name === 'children',
);
function getChildrenArr(rootNode) {
  const result = rootNode.properties.find(
    (node) => node.key && node.key.name === 'children',
  );
  if (result) {
    return result.value;
  } else {
    return null;
  }
}
function getValueByKey(rootNode, key) {
  if (t.isObjectExpression(rootNode)) {
    const asminode = rootNode.properties.find(
      (node) => node.key && node.key.name === key,
    );
    if (!asminode) {
      return null;
    }
    if (
      t.isStringLiteral(asminode.value) ||
      t.isNumericLiteral(asminode.value)
    ) {
      return asminode.value.value;
    } else if (t.isObjectExpression(asminode.value)) {
      return getObjValue(asminode.value);
    } else {
      return null;
    }
  } else {
    return null;
  }
}
function getObjValue(ObjectExpression) {
  if (t.isObjectExpression(ObjectExpression)) {
    const _obj = {};
    ObjectExpression.properties.forEach((n) => {
      _obj[n.key.name] = getValueByKey(ObjectExpression, n.key.name);
    });
    return _obj;
  } else {
    return null;
  }
}
const mapTree = (dataArr) => {
  return dataArr.elements.map((item) => {
    const name = getValueByKey(item, 'name');
    const path = getValueByKey(item, 'path');
    const redirect = getValueByKey(item, 'redirect');
    const meta = getValueByKey(item, 'meta');
    let children = [];
    if (getChildrenArr(item)) {
      children = mapTree(getChildrenArr(item));
    } else {
      children = null;
    }
    return { name, path, redirect, meta, children };
  });
};

module.exports = () => mapTree(pagesNodeArr.value);
