import { CATEGORIES, BLOCK_SEQUENCE } from "../../../configuration/constants";
const BlockManager = (editor, opts = {}) => {
  editor.on('load', () => {
    const blockManager = editor.BlockManager;

    // 组件排序
    const visibleBlocks = blockManager.getAll().filter(block => {
      const category = block.get('category');

      if (category) {
        return category.get('label') !== CATEGORIES.INVISIBLE;
      }

      return true;
    });

    const getBlockIndex = (blockLabel) => {
      for (let index = 0; index < BLOCK_SEQUENCE.length; index++) {
        if (blockLabel.indexOf(BLOCK_SEQUENCE[index]) > -1) {
          return index;
        }
      }
      return BLOCK_SEQUENCE.length;
    }
    visibleBlocks.sort((a, b) => {
      const aIndex = getBlockIndex(a.get('label'));
      const bIndex = getBlockIndex(b.get('label'));

      return aIndex - bIndex;
    });

    editor.BlockManager.allVisibleBlocks = visibleBlocks;
    blockManager.render(visibleBlocks);

    // 获取内置组件标签名，设置图层元素对应名称
    editor.BlockManager.getAll().models.map(val => {
      if (val.attributes.hasOwnProperty('label')) {
        const label = val.attributes.label;
        const type = editor.DomComponents.getType(val.id);

        if (type) {
          if (label.indexOf("</svg>") > 0 && label.indexOf("</div>") > 0) {
            const rep = />(.*)(<\/div>)/
            const str = label.toString().match(rep);
            type.model.prototype.defaults.name = str[1];
          } else {
            type.model.prototype.defaults.name = label;
          }
        }
      }
    });
  })
};

export default BlockManager;
