const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackIncludeAssetsPlugin = require('html-webpack-include-assets-plugin');
const WebpackDevServer = require('webpack-dev-server');
const argv = require('yargs').argv;
const [, , port] = process.argv;

const ROOT = process.cwd();

const DIST = path.resolve(ROOT, 'dist', 'ide');
const {getLoaderAbsolutePath} = require('./utils');

function resolve(dir) {
    return path.join(ROOT, dir);
}

const config = {
    mode: 'development',
    // mode: 'production',
    devtool: '#cheap-module-eval-source-map',
    entry: path.join(__dirname, 'entry.ide.js'),
    output: {
        filename: 'render.js',
        path: DIST,
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: [resolve('src'), resolve('node_modules/webpack-dev-server/client')]
            },
            {
                test: /\.ts$/,
                use: [{
                    loader: 'babel-loader'
                },
                {
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true,
                        appendTsSuffixTo: [
                            '\\.vue$'
                        ]
                    }
                }]
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000
                }
            },
            {
                test: /\.pug$/,
                oneOf: [
                    // 这条规则应用到 Vue 组件内的 `<template lang="pug">`
                    {
                        resourceQuery: /^\?vue/,
                        use: [
                            'pug-plain-loader'
                        ]
                    },
                    // 这条规则应用到 JavaScript 内的 pug 导入
                    {
                        use: ['raw-loader', 'pug-plain-loader']
                    }
                ]
            },
            {
                test: /\.css$/,
                use: ['vue-style-loader', getLoaderAbsolutePath('css-loader'),]
            },
            {
                test: /\.less$/,
                use: ['vue-style-loader', getLoaderAbsolutePath('css-loader'), 'less-loader']
            },
            {
                test: /\.styl$/,
                use: ['vue-style-loader', getLoaderAbsolutePath('css-loader'), 'postcss-loader', 'stylus-loader']
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 20000
                }
            },
            {
                test: /bili-small-app\/runtime\/bl/,
                use: [
                    { loader: 'babel-loader' },
                    {
                        loader: 'string-replace-loader',
                        options: {
                            search: '__BLJS__',
                            replace: 'import bl from \'./bl.web\'',
                            flags: 'g'
                        }
                    }
                ]
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            '@': ROOT
        }
    },
    plugins: [
        new webpack.DefinePlugin({
            IS_SMALL_GAME: 'false'
        }),
        new VueLoaderPlugin(),
        new CleanWebpackPlugin(DIST, {
            root: ROOT,
            verbose: false
        }),
        new CopyWebpackPlugin([
            {
                from: path.join(path.dirname(__dirname), 'dev'),
                to: path.join(DIST, 'static'),
                ignore: ['.*']
            },
            {
                from: path.join(ROOT, 'static'),
                to: path.join(DIST, 'static')
            }
        ]),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: path.join(__dirname, 'template.html'),
            inject: true
        }),
        new HtmlWebpackIncludeAssetsPlugin({
            assets: ['static/vue.runtime.js'],
            append: false
        }),
    ],
    externals: {
        vue: 'Vue'
    },
    devServer: {
        // host: '127.0.0.1',
        // port: argv.port,
        contentBase: path.join(ROOT, 'static'),
        open: false,
        disableHostCheck: true,
        proxy: {
            '/api/miniapp': {
                target: 'http://miniapp.bilibili.com',
                secure: false,
                changeOrigin: true
            },
            '/api/applet': {
                target: 'http://miniapp.bilibili.com',
                secure: false,
                changeOrigin: true
            },
            '/api': {
                target: 'https://mall.bilibili.com/mall-c',
                secure: false,
                changeOrigin: true
            },
            '/miniapp-b/miniapp': {
                target: 'http://miniapp.bilibili.com',
                secure: false,
                changeOrigin: true
            },
            '/ticket': {
                target: 'http://show.bilibili.com/api',
                secure: false,
                changeOrigin: true
            },
            '/cart/na': {
                target: 'https://mall.bilibili.com/mall-c',
                secure: false,
                changeOrigin: true
            }
        }
    }
};

const server = new WebpackDevServer(webpack(config), {
    inline: true,
    progress: true,
    ...config.devServer
});

server.listen(port, '127.0.0.1', function (err) {
    if (err) {
      console.log(err);
    }
    console.log('WebpackDevServer listening at localhost:', port);
});
