const path = require('path');
const fs = require('fs');
const escodegen = require('escodegen');
const glob = require('glob');
const makeServiceImports = require('./makeServiceImports');
const { _root, _src } = require('./getBlConfig');
const jsonConditionalCompilation = require('./jsonConditionalCompilation');

module.exports = function () {
    // this.resourcePath
    // service.js path is ROOT/src/service.js
    // 取到所有vue文件，其中一部分是page入口，其他全是component
    const SRC = path.join(this.rootContext, _root, _src);

    // const vues = glob.sync(path.join(SRC, '**/*.vue'));

    let appJson = fs.readFileSync(path.join(SRC, 'app.json'), 'utf8');
    appJson = jsonConditionalCompilation({
        content: appJson,
        platform: 'bl'
    });
    appJson = JSON.parse(appJson);
    let entries = [];
    appJson.pages.forEach((conf) => {
        entries.push(`.${_root}${_src}${conf.path}/index.vue`); // ./src...
    });

    // 构建 import components && comp config map
    const serviceImports = makeServiceImports(entries);

    // insert pages && components to service.js
    let insertAst = {
        "type": "Program",
        "body": [
            {
                "type": "ImportDeclaration",
                "specifiers": [],
                "source": {
                    "type": "Literal",
                    "value": "bili-small-app/runtime/header",
                    "raw": "'bili-small-app/runtime/header'",
                },
            },
            {
                "type": "ImportDeclaration",
                "specifiers": [],
                "source": {
                    "type": "Literal",
                    "value": "%/app.js",
                    "raw": "'%/app.js'",
                },
            }
        ],
        "sourceType": "module",
    };

    insertAst.body.push(...serviceImports);
    const importCode = escodegen.generate(insertAst);
    // append 
    const appendCode = fs.readFileSync(path.join(path.dirname(__dirname), 'runtime', 'service.js'), 'utf8');

    return importCode + appendCode;
};
