// https://webpack.docschina.org/contribute/writing-a-loader/
const { parse } = require('@vue/compiler-sfc');

const insertBeforeComp = compName => (match, attributes, content) => {
  const modifiedContent = `<my-tree-select />${content}`;
  return `<${compName}${attributes}>${modifiedContent}</${compName}>`;
};

module.exports = function (source) {
  // const options = this.getOptions();

  // const regex = /<tl-filter-left(.*?)>([\s\S]*?)<\/tl-filter-left>/gs;
  const regexFirst = /<tl-filter-left(.*?)>([\s\S]*?)<\/tl-filter-left>/g;
  const regexSecond = /<tl-filter(.*?)>([\s\S]*?)<\/tl-filter>/g;
  // 使用 ast 解析更加严谨
  const { descriptor } = parse(source);
  if (descriptor.template && descriptor.template.content) {
    const templateContent = descriptor.template.content;
    let compName = '',
      isMatch = false,
      regex;

    // const isMatch =
    //   templateContent.match(regexFirst) || templateContent.match(regexSecond);

    if (templateContent.match(regexFirst)) {
      compName = 'tl-filter-left';
      isMatch = true;
      regex = regexFirst;
    } else if (templateContent.match(regexSecond)) {
      compName = 'tl-filter';
      isMatch = true;
      regex = regexSecond;
    }
    if (isMatch && compName !== '' && regex) {
      // 找到模版的 tl-filter 或者 tl-filter-left 组件（优先），在组件的子元素最前面加入 my-tree-select 组件
      const _insertBeforeComp = insertBeforeComp(compName);
      const updatedTemplateContent = templateContent.replace(
        regex,
        _insertBeforeComp
      );
      // console.log('updatedTemplateContent :>> ', updatedTemplateContent);
      source = source.replace(
        descriptor.template.content,
        updatedTemplateContent
      );
    }
    return source;
  }
  return source;
};
