var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    mode: process.env.NODE_ENV,
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, '../public'),
        publicPath: '/',
        filename: 'build.js',
    },
    // optimization: {
    //     runtimeChunk: 'single',
    //     // minimizer: [new UglifyJsPlugin()],
    //     // minimize: false,
    //     splitChunks: {
    //         chunks: 'all',
    //         maxInitialRequests: Infinity,
    //         minSize: 0,
    //         cacheGroups: {
    //             vendor: {
    //                 test: /[\\/]node_modules[\\/]/,
    //                 name(module) {
    //                     // get the name. E.g. node_modules/packageName/not/this/part.js
    //                     // or node_modules/packageName
    //                     const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

    //                     // npm package names are URL-safe, but some servers don't like @ symbols
    //                     return `npm.${packageName.replace('@', '')}`;
    //                 },
    //             },
    //         },
    //     },
    // },
    module: {
        rules: [{
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    plugins: [
                        "@babel/plugin-syntax-dynamic-import"
                    ]
                }
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    compilerOptions: {
                        modules: [{
                            preTransformNode(astEl) {
                                if (process.env.NODE_ENV === "production") {
                                    const { attrsMap, attrsList } = astEl;
                                    if (attrsMap["data-cy"]) {
                                        delete attrsMap["data-cy"];
                                        const index = attrsList.findIndex(x => x.name === 'data-cy')
                                        attrsList.splice(index, 1);
                                    }
                                }
                                return astEl;
                            }
                        }]
                    }
                    // other vue-loader options go here
                }
            },
            {
                test: /\.s(c|a)ss$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    {
                        loader: 'sass-loader',
                        options: {
                            implementation: require('sass'),
                            fiber: require('fibers'),
                            indentedSyntax: true // optional
                        }
                    }
                ]
            },
            {
                test: /\.less$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'less-loader'
                ]
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'fontsDirectory/'
                    }
                }]
            },
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ],
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: 'images/[name].[ext]?[hash:8]'
                }
            },
            {
                test: /\.html$/,
                use: [
                    // {
                    //     loader: "file-loader",
                    //     options: {
                    //         name: "[name].html"
                    //     }
                    // },
                    // {
                    //     loader: "extract-loader"// tells webpack to not include html file into mainbundle js
                    // },
                    {
                        loader: "html-loader",
                        options: {
                            attrs: ["img:src"] // the src attribute in img element of html is the target
                        }
                    }
                ]
            },

        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
    },
    devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true,
        hot: true,
        open: true
    },
    performance: {
        hints: false
    },
    devtool: '#eval-source-map',
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new VueLoaderPlugin(),
    ]
}
if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = ''
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new HtmlWebpackPlugin({

            template: 'index.html',
            filename: path.resolve(__dirname, '../public/index.html'),
            // filename: "index.html",
            favicon: 'favicon.ico'
        }),
        new PrerenderSPAPlugin({
            staticDir: path.join(__dirname, '../public'),
            routes: ['/'],
            indexPath: path.join(__dirname, '../public', 'index.html'),
            minify: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                decodeEntities: true,
                keepClosingSlash: true,
                sortAttributes: true
            },
            renderer: new Renderer({
                inject: {
                    foo: 'bar'
                },
                headless: true,
                renderAfterDocumentEvent: 'render-event'
            })
        })
    ])
} else {
    // NODE_ENV === 'development'
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"development"'
            }
        }),
        new HtmlWebpackPlugin({

            template: 'index.html',
            filename: path.resolve(__dirname, '../public/index.html'),
            favicon: 'favicon.ico'
        }),
    ])
}