"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _slugid = _interopRequireDefault(require("slugid"));
var _constants = require("../constants");
var _helper = require("../helper");
const codeBlockRule = (element, parseChild) => {
  const {
    nodeName,
    childNodes
  } = element;
  if (nodeName === 'PRE') {
    const children = Array.from(childNodes).filter(item => item.nodeName === 'CODE');
    let codeChild = children[0];
    if (codeChild) {
      let lang = codeChild.getAttribute('lang');
      lang = (0, _helper.genCodeLangs)().find(item => item.value === lang) || 'plaintext';
      return {
        id: _slugid.default.nice(),
        language: lang,
        type: _constants.CODE_BLOCK,
        children: parseChild(children)
      };
    } else {
      const lang = 'plaintext';
      const content = childNodes[0].textContent;
      const textArr = content.split('\n').filter(Boolean);
      const children = textArr.map(text => {
        return {
          id: _slugid.default.nice(),
          type: _constants.CODE_LINE,
          children: [{
            id: _slugid.default.nice(),
            text: text
          }]
        };
      });
      return {
        id: _slugid.default.nice(),
        language: lang,
        type: _constants.CODE_BLOCK,
        children: children
      };
    }
  }
  if (nodeName === 'CODE' && element.parentElement.nodeName === 'PRE') {
    const childIsP = Array.from(childNodes).every(n => n.nodeName === 'P');
    if (childIsP) {
      return Array.from(childNodes).map(n => {
        return {
          id: _slugid.default.nice(),
          type: _constants.CODE_LINE,
          children: [{
            id: _slugid.default.nice(),
            text: n.textContent
          }]
        };
      });
    }
    const content = element.textContent;
    const hasNewLine = content.indexOf('\n') > -1;
    if (!hasNewLine) {
      return {
        id: _slugid.default.nice(),
        type: _constants.CODE_LINE,
        children: [{
          id: _slugid.default.nice(),
          text: element.textContent
        }]
      };
    }
    const codes = content.split('\n').filter(Boolean);
    return codes.map(item => {
      return {
        id: _slugid.default.nice(),
        type: _constants.CODE_LINE,
        children: [{
          id: _slugid.default.nice(),
          text: item
        }]
      };
    });
  }
  return;
};
var _default = exports.default = codeBlockRule;