
const fs = require('fs');
const path = require('path');
const acorn = require('acorn');
const escodegen = require('escodegen');
const getInjectTpl = require('./template/injection');

module.exports = function blSappRenderPreLoader (source) {
    const vueFileContent = fs.readFileSync(this.resourcePath, 'utf8');

    const isWebviewOnly = vueFileContent.substr(0, 21) === '<!-- webview only -->';

    if (vueFileContent.substr(0, 21) === '<!-- webview only -->' || this.resourceQuery) {
        return source;
    }
  
    const ast = acorn.parse(source, {
        sourceType: 'module'
    });

    let hasScriptImport = false;
    let importEndIndex = 0;
    ast.body.forEach((ele, idx) => {
        if (ele.type === 'ImportDeclaration') {
            importEndIndex = idx;

            if (ele.specifiers.find(spec => {
                return spec.local && spec.local.name === 'script';
            })) {
                hasScriptImport = true;
            }
        }
    });

    if (hasScriptImport) {
        const SRC = path.join(this.rootContext, 'src/');
        const biliPath = this.resourcePath.replace(SRC, '').slice(0, -4); // 剔除 src前面 的路径和‘.vue’后的值
        const tpl = getInjectTpl(biliPath, isWebviewOnly);

        const astTpl = acorn.parse(tpl, {
            sourceType: 'module'
        });
        ast.body.splice(importEndIndex + 1, 0, ...astTpl.body);
    }

    return escodegen.generate(ast);
};