import { exec } from 'child_process'
import { EnvironmentPlugin, DefinePlugin } from 'webpack'
import ForkTsPlugin from 'fork-ts-checker-webpack-plugin'
import CopyPlugin from 'copy-webpack-plugin'
import HtmlPlugin from 'html-webpack-plugin'
import HtmlIncAssetsPlugin from 'html-webpack-include-assets-plugin'
import HardSourcePlugin from 'hard-source-webpack-plugin'
import StylelintPlugin from 'stylelint-webpack-plugin'
import BuildNotifPlugin from 'webpack-build-notifier'
import CssExtractPlugin from 'mini-css-extract-plugin'
import SentryPlugin from '@sentry/webpack-plugin'
import ZipPlugin from 'zip-webpack-plugin'
import PostCompilePlugin from 'post-compile-webpack-plugin'
const Dotenv = require('dotenv-webpack')

// Disabling this for now as it adds 2-4 seconds to inc. build time - look into finding out why
// import WebExtReloadPlugin from 'webpack-chrome-extension-reloader'

import initEnv from './env'
import * as staticFiles from './static-files'
import { output } from './config'

/**
 * @param {boolean} tslint Denotes whether or not to enable linting on this thread as well as type checking.
 */
const initTsPlugin = (tslint) =>
    new ForkTsPlugin({
        checkSyntacticErrors: true,
        async: false,
        tslint,
    })

export default function ({
    webExtReloadPort = 9090,
    mode = 'development',
    template,
    isCI = false,
    runSentry = false,
    notifsEnabled = false,
    shouldPackage = false,
    packagePath = '../dist',
    extPackageName = 'extension.zip',
    sourcePackageName = 'source-code.zip',
}) {
    const envs = initEnv({ mode })
    const plugins = [
        new EnvironmentPlugin(envs),
        new Dotenv(),
        new CopyPlugin(staticFiles.copyPatterns),
        new HtmlPlugin({
            title: 'Popup',
            chunks: ['popup'],
            filename: 'popup.html',
            template,
        }),
        new HtmlPlugin({
            title: 'Memex',
            chunks: ['options'],
            filename: 'options.html',
            template,
        }),
        new HtmlIncAssetsPlugin({
            append: false,
            assets: staticFiles.htmlAssets,
        }),
        new CssExtractPlugin({
            filename: '[name].css',
        }),
    ]

    if (mode === 'development') {
        plugins.push(
            new HardSourcePlugin({
                environmentHash: {
                    root: process.cwd(),
                    directories: [],
                    files: ['package-lock.json', 'yarn.lock', '.env'],
                },
            }),
            // new WebExtReloadPlugin({
            //     port: webExtReloadPort,
            // }),
        )
    } else if (mode === 'production') {
        plugins.push(
            new SentryPlugin({
                release: process.env.npm_package_version,
                include: output.path,
                dryRun: !runSentry,
            }),
        )
    }

    // CI build doesn't need to use linting plugins
    if (isCI) {
        return [...plugins, initTsPlugin(false)]
    }

    if (notifsEnabled) {
        plugins.push(
            new BuildNotifPlugin({
                title: 'Memex Build',
            }),
        )
    }

    if (shouldPackage) {
        plugins.push(
            new ZipPlugin({
                path: packagePath,
                filename: extPackageName,
                exclude: [/\.map/],
            }),
            new PostCompilePlugin(() =>
                exec('git-archive-all dist/source-code.zip'),
            ),
        )
    }

    return [
        ...plugins,
        initTsPlugin(true),
        new StylelintPlugin({
            files: 'src/**/*.css',
            failOnError: mode === 'production',
        }),
    ]
}

@@ -60,22 +60,8 @@
 ugin
-, DefinePlugin
  %7D f
@@ -670,217 +670,8 @@
 in'%0A
-const Dotenv = require('dotenv-webpack')%0A%0A// Disabling this for now as it adds 2-4 seconds to inc. build time - look into finding out why%0A// import WebExtReloadPlugin from 'webpack-chrome-extension-reloader'%0A%0A
 impo
@@ -773,16 +773,57 @@
 /config'
+%0Aconst Dotenv = require('dotenv-webpack')
 %0A%0A/**%0A *
@@ -2372,110 +2372,8 @@
 %7D),%0A
-            // new WebExtReloadPlugin(%7B%0A            //     port: webExtReloadPort,%0A            // %7D),%0A
     
@@ -2644,246 +2644,198 @@
     
-// CI build doesn't need to use linting plugins%0A    if (isCI) %7B%0A        return %5B...plugins, initTsPlugin(false)%5D
+if (shouldPackage %7C%7C isCI) %7B%0A        plugins.push(%0A            new ZipPlugin(%7B
 %0A    
-%7D%0A%0A
     
-if (notifsEnabled) %7B%0A        plugins.push(%0A            new BuildNotifPlugin(%7B%0A                title: 'Memex Build'
+        path: packagePath,%0A                filename: extPackageName,%0A                exclude: %5B/%5C.map/%5D
 ,%0A  
@@ -2924,35 +2924,47 @@
         new 
-Zip
+PostCompile
 Plugin(
-%7B
+() =%3E
 %0A           
@@ -2968,33 +2968,75 @@
         
-path: packagePath
+exec('git-archive-all dist/source-code.zip'),%0A            )
 ,%0A      
@@ -3041,93 +3041,187 @@
     
+)%0A
     
+%7D%0A%0A
     
-filename: extPackageName,%0A                exclude: %5B/%5C.map/%5D,
+// CI build doesn't need to use linting plugins%0A    if (isCI) %7B%0A        return %5B...plugins, initTsPlugin(false)%5D
 %0A    
+%7D%0A%0A
     
-    %7D),
+if (notifsEnabled) %7B%0A        plugins.push(
 %0A   
@@ -3233,39 +3233,34 @@
     new 
-PostCompile
+BuildNotif
 Plugin(
-() =%3E
+%7B
 %0A       
@@ -3272,52 +3272,28 @@
     
-exec('git-archive-all dist/source-code.zip')
+title: 'Memex Build'
 ,%0A  
@@ -3294,32 +3294,33 @@
 d',%0A            
+%7D
 ),%0A        )%0A   

Update CI build to also create compiled web ext ZIP