const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const vueLoaderConfig = require('../vue-loader.conf');
const { _config } = require('../getBlConfig');
const jsonConditionalCompilation = require('../jsonConditionalCompilation');

module.exports = (ROOT, SRC, mode = 'production') => {
    const DIST = path.join(ROOT, _config, 'dist');

    fs.writeFileSync(path.resolve('./src/service.js'), '', 'utf8');

    let blConfig = { isUni: true };

    if (fs.existsSync(path.join(ROOT, 'bl.config.js'))) {
        blConfig = require(path.join(ROOT, 'bl.config.js'));
        if (blConfig.isUni === undefined) {
            blConfig.isUni = true;
        }
    }

    let appJson = fs.readFileSync(path.join(SRC, 'app.json'), 'utf8');
    let packageJson = fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8');
    let _jsonData = JSON.parse(appJson);
    let _packageJson = JSON.parse(packageJson);

    let entries = {
        '/': './src/service.js'
    };

    appJson = jsonConditionalCompilation({
        content: appJson,
        platform: 'bl'
    });

    const configs = {
        node: {
            fs: 'empty'
        },
        mode: mode,
        entry: entries,
        output: {
            globalObject: 'this',
            filename: '[name]service.js',
            chunkFilename: '[name].service.js',
            path: DIST,
        },
        module: {
            rules: [{
                test: /\.vue$/,
                use: [
                    { loader: path.resolve(__dirname, '../loaders/uni-vue-post-loader')},
                    { loader: path.resolve(__dirname, '../loaders/bl-sapp-service-post-loader') },
                    {
                        loader: 'vue-loader',
                        options: vueLoaderConfig,
                    },
                    { loader: path.resolve(__dirname, '../loaders/bl-sapp-service-pre-loader') }
                ],
            },
            {
                test: /\.js$/,
                use: [{
                    loader: 'babel-loader'
                },
                {
                    loader: 'uni-js-loader',
                    options: {
                        platform: 'bl'
                    }
                }
                ],
                include: [
                    SRC,
                    path.join(
                        ROOT,
                        'node_modules',
                        'bili-small-app',
                        'runtime'
                    ),
                    path.join(
                        ROOT,
                        'node_modules',
                        'bili-small-app',
                        'components'
                    ),
                ]
            },
            {
                test: /\.ts$/,
                use: [{
                    loader: 'babel-loader'
                },
                {
                    loader: 'uni-js-loader',
                    options: {
                        platform: 'bl'
                    }
                }, {
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true,
                        appendTsSuffixTo: [
                            '\\.vue$'
                        ]
                    }
                }]
            },
            {
                test: /\.(png|jpe?g|gif|svg)$/,
                loader: 'null-loader',
            },
            {
                test: /service\.js$/,
                use: [
                    { loader: 'babel-loader' },
                    { loader: path.resolve(__dirname, '../splitChunksConfig/service-loader')},
                ],
            },
            {
                test: /small-app[/\\]runtime[/\\]bl/,
                use: [
                    { loader: 'babel-loader' },
                    {
                        loader: 'string-replace-loader',
                        options: {
                            search: '__BLJS__',
                            replace: "import bl from './bl.app'",
                            flags: 'g',
                        },
                    },
                ],
            },
            {
                test: /\.pug$/,
                oneOf: [
                    // 这条规则应用到 Vue 组件内的 `<template lang="pug">`
                    {
                        resourceQuery: /^\?vue/,
                        use: [
                            {
                                loader: path.resolve(__dirname, '../loaders/uni-vue-post-loader')
                            },
                            'pug-plain-loader'
                        ]
                    },
                    // 这条规则应用到 JavaScript 内的 pug 导入
                    {
                        use: ['raw-loader', 'pug-plain-loader']
                    }
                ]
            },
            {
                test: /\.json$/,
                use: [{
                    loader: 'uni-json-loader',
                    options: {
                        platform: 'bl'
                    }
                }],
            },
            {
                test: /\.css$/,
                use: [
                    'null-loader'
                ]
            },
            {
                test: /\.less$/,
                use: [
                    'null-loader'
                ]
            },
            {
                test: /\.styl$/,
                use: [
                    'null-loader'
                ]
            },
            ],
        },
        resolve: {
            extensions: ['.js', '.vue', '.json', '.styl'],
            alias: {
                '@': ROOT,
                '%': SRC
            },
            mainFields: ['main']
        },
        plugins: [
            new VueLoaderPlugin(),
            new webpack.DefinePlugin({
                GLOBAL_OBJECT: 'Service',
                IS_SMALL_GAME: 'false',
                'process.env': require('../config').env,
                APPID: '"' + JSON.parse(fs.readFileSync(path.join(ROOT, _config, '.sapprc'), 'utf8')).appId + '"',
                APP_JSON: appJson,
                SAPP_BUILDTIME: '"' + new Date().getTime() + '"',
                SAPP_VERSION: '"' + _packageJson.version + '"',
                SAPP_SMALLAPP: '"' + _packageJson.dependencies['bili-small-app'] + '"'
            })
        ],
        externals: {
            vue: 'Vue'
        }
    };
    if (process.env.BL_NOMIN) {
        configs.optimization = {
            minimize: false
        };
    }
    return configs;
};
