const { join, resolve, dirname } = require('path');
const Encore = require('@symfony/webpack-encore');
const { VueLoaderPlugin } = require('vue-loader');

const babelLoader = {
    // test: /\.js$/,
    test: /\.(js|jsx|ts|tsx)$/,
    // exclude: /(node_modules|bower_components)/,
    // exclude: file => (
    //   /node_modules/.test(file) &&
    //   !/\.vue\.js/.test(file)
    // ),
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: [
                // ['@babel/preset-env', {
                //   "targets": "> 0.25%, not dead"
                //   // "targets": {
                //   //   "edge": "17",
                //   //   "firefox": "60",
                //   //   "chrome": "67",
                //   //   "safari": "11.1"
                //   // }
                // }],
                ['@babel/preset-env', {}],
                'babel-preset-typescript-vue3', //because of new vue setup method
                // "@babel/preset-typescript"
            ],
            plugins: [
                // "@babel/plugin-transform-runtime",
                ['@babel/plugin-proposal-decorators', { legacy: true }],

                '@babel/proposal-class-properties',
            ],
        },
    },
};

// const Components = require('unplugin-vue-components/webpack')
// const { NaiveUiResolver } = require('unplugin-vue-components/resolvers')

/*
|--------------------------------------------------------------------------
| Encore runtime environment
|--------------------------------------------------------------------------
*/
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

/*
|--------------------------------------------------------------------------
| Output path
|--------------------------------------------------------------------------
|
| The output path for writing the compiled files. It should always
| be inside the public directory, so that AdonisJS can serve it.
|
*/
Encore.setOutputPath('./public/assets');

/*
|--------------------------------------------------------------------------
| Public URI
|--------------------------------------------------------------------------
|
| The public URI to access the static files. It should always be
| relative from the "public" directory.
|
*/
Encore.setPublicPath('/assets');

/*
|--------------------------------------------------------------------------
| Entrypoints
|--------------------------------------------------------------------------
|
| Entrypoints are script files that boots your frontend application. Ideally
| a single entrypoint is used by majority of applications. However, feel
| free to add more (if required).
|
| Also, make sure to read the docs on "Assets bundler" to learn more about
| entrypoints.
|
*/
Encore.addEntry('app', './resources/js/app.js');

/*
|--------------------------------------------------------------------------
| Copy assets
|--------------------------------------------------------------------------
|
| Since the edge templates are not part of the Webpack compile lifecycle, any
| images referenced by it will not be processed by Webpack automatically. Hence
| we must copy them manually.
|
*/
// Encore.copyFiles({
//   from: './resources/images',
//   to: 'images/[path][name].[hash:8].[ext]',
// })

/*
|--------------------------------------------------------------------------
| Split shared code
|--------------------------------------------------------------------------
|
| Instead of bundling duplicate code in all the bundles, generate a separate
| bundle for the shared code.
|
| https://symfony.com/doc/current/frontend/encore/split-chunks.html
| https://webpack.js.org/plugins/split-chunks-plugin/
|
*/
// Encore.splitEntryChunks()

/*
|--------------------------------------------------------------------------
| Isolated entrypoints
|--------------------------------------------------------------------------
|
| Treat each entry point and its dependencies as its own isolated module.
|
*/
Encore.disableSingleRuntimeChunk();

/*
|--------------------------------------------------------------------------
| Cleanup output folder
|--------------------------------------------------------------------------
|
| It is always nice to cleanup the build output before creating a build. It
| will ensure that all unused files from the previous build are removed.
|
*/
Encore.cleanupOutputBeforeBuild();

/*
|--------------------------------------------------------------------------
| Source maps
|--------------------------------------------------------------------------
|
| Enable source maps in production
|
*/
Encore.enableSourceMaps(!Encore.isProduction());

/*
|--------------------------------------------------------------------------
| Assets versioning
|--------------------------------------------------------------------------
|
| Enable assets versioning to leverage lifetime browser and CDN cache
|
*/
Encore.enableVersioning(Encore.isProduction());

/*
|--------------------------------------------------------------------------
| Configure dev server
|--------------------------------------------------------------------------
|
| Here we configure the dev server to enable live reloading for edge templates.
| Remember edge templates are not processed by Webpack and hence we need
| to watch them explicitly and livereload the browser.
|
*/
Encore.configureDevServerOptions((options) => {
    /**
     * Normalize "options.static" property to an array
     */
    if (!options.static) {
        options.static = [];
    } else if (!Array.isArray(options.static)) {
        options.static = [options.static];
    }

    /**
     * Enable live reload and add views directory
     */
    options.liveReload = true;
    options.static.push({
        directory: join(__dirname, './resources/views'),
        watch: true,
    });
});

/*
|--------------------------------------------------------------------------
| CSS precompilers support
|--------------------------------------------------------------------------
|
| Uncomment one of the following lines of code to enable support for your
| favorite CSS precompiler
|
*/
// Encore.enableSassLoader()
// Encore.enableLessLoader()
// Encore.enableStylusLoader()

/*
|--------------------------------------------------------------------------
| CSS loaders
|--------------------------------------------------------------------------
|
| Uncomment one of the following line of code to enable support for
| PostCSS or CSS.
|
*/
Encore.enablePostCssLoader();
// Encore.configureCssLoader(() => {})

/*
|--------------------------------------------------------------------------
| Enable Vue loader
|--------------------------------------------------------------------------
|
| Uncomment the following lines of code to enable support for vue. Also make
| sure to install the required dependencies.
|
*/
// Encore.configureBabel(function(config) {
//   config.presets.push('@babel/preset-env');
//   config.presets.push('babel-preset-typescript-vue3');
//   config.presets.push('@babel/preset-typescript');
//   config.plugins.push(["@babel/plugin-proposal-decorators", { "legacy": true }]);
//   config.plugins.push("@babel/proposal-class-properties");
// }, {
//     // useBuiltIns: 'usage',
//     // corejs: 3,
//     // exclude:  /(node_modules|bower_components)/,
//   })

// Encore.configureBabel(() => {
//   // // babelConfig.presets.push('@babel/preset-typescript');
//   // // babelConfig.plugins.push('@babel/plugin-proposal-decorators');
//   // // babelConfig.plugins.push('@babel/plugin-proposal-class-properties');
// }, {
//   // useBuiltIns: 'usage',
//   // corejs: 3,
//   // exclude:  /(node_modules|bower_components)/,
// })

// Encore.addLoader(babelLoader)
// .addAliases({
//   '@': join(__dirname, 'resources/js')
// }).configureDefinePlugin(options => {
//   options['__VUE_OPTIONS_API__'] = true
//   options['__VUE_PROD_DEVTOOLS__'] = false
// })

// Encore.enableVueLoader(() => {}, {
//   version: 3,
//   runtimeCompilerBuild: true,  //if using only single file components, this is not needed (https://symfony.com/doc/current/frontend/encore/vuejs.html#runtime-compiler-build)
//   useJsx: false,

//     // transpileOnly: true, //delet not valid
//     // appendTsSuffixTo: [
//     //   '\\.vue$'
//     // ],
//     // happyPackMode: false
//   // options: {
//   //   loaders: {
//   //     ts: 'babel-loader!ts-loader'
//   //   }
//   // }
// })
Encore.addLoader({
    test: /\.vue$/,
    loader: 'vue-loader',
    options: {
        // loaders: {
        // 	ts: 'ts-loader',
        // },
        cacheDirectory: 'C:\\Users\\kaiarn\\Documents\\Software\\tethys.viewer\\node_modules\\.cache\\vue-loader',
        cacheIdentifier: 'f930df3e',
        babelParserPlugins: ['jsx', 'classProperties', 'decorators-legacy'],
    },
}).addPlugin(new VueLoaderPlugin());
// .addAliases({
// 	vue$: 'vue/dist/vue.runtime.esm-bundler.js',
// });

Encore.addLoader(babelLoader)
    // Encore.enableTypeScriptLoader(config => {
    // 	 // Loader-specific options
    // 	config.configFile = 'tsconfig.vue.json';
    // 	config.appendTsSuffixTo = [/\.vue$/];
    // 	config.transpileOnly = true;
    // 	config.happyPackMode = false;
    // }, {
    // 	// Directly change the exclude rule
    // 	exclude: /node_modules/,

    // })
    .addAliases({
        '@': join(__dirname, 'resources/js'),
        'vue$': 'vue/dist/vue.runtime.esm-bundler.js',
    })
    .configureDefinePlugin((options) => {
        options['__VUE_OPTIONS_API__'] = true;
        options['__VUE_PROD_DEVTOOLS__'] = false;
    });

// Encore.addAliases({
//   '@': resolve(__dirname, 'resources/js')
// })

// Encore.addPlugin(Components({
//   resolvers: [NaiveUiResolver()]
// }))

// uncomment if you use TypeScript
// Encore.enableTypeScriptLoader()
// Encore.addLoader(babelLoader)

// Encore.configureTerserPlugin((options) => {
// 	options.extractComments = false;
// 	options.parallel = true;
// 	options.terserOptions = {
// 		compress: {
// 			arrows: false,
// 			collapse_vars: false,
// 			comparisons: false,
// 			computed_props: false,
// 			hoist_funs: false,
// 			hoist_props: false,
// 			hoist_vars: false,
// 			inline: false,
// 			loops: false,
// 			negate_iife: false,
// 			properties: false,
// 			reduce_funcs: false,
// 			reduce_vars: false,
// 			switches: false,
// 			toplevel: false,
// 			typeofs: false,
// 			booleans: true,
// 			if_return: true,
// 			sequences: true,
// 			unused: true,
// 			conditionals: true,
// 			dead_code: true,
// 			evaluate: true,
// 		},
// 		mangle: {
// 			safari10: true,
// 		},
// 	};
// });

/*
|--------------------------------------------------------------------------
| Configure logging
|--------------------------------------------------------------------------
|
| To keep the terminal clean from unnecessary info statements , we only
| log warnings and errors. If you want all the logs, you can change
| the level to "info".
|
*/
const config = Encore.getWebpackConfig();
config.infrastructureLogging = {
    level: 'warn',
};
config.stats = 'errors-warnings';
// config.resolve.extensions.push('.vue');
// config.resolve.extensions.push('.ts');
// config.resolve.extensions.push('.js');
// Encore.addAliases({
//   vue$: 'vue/dist/vue.runtime.esm-bundler.js'
// })
// config.resolve = {
//   extensions: ['.vue', '.ts', '.js'],
// //   alias: {
// //       // Base: path.resolve(__dirname, './remark/es/Base.js'),
// //       // Site: path.resolve(__dirname, './remark/es/Site.js'),
// //       // '@':  path.resolve(__dirname, 'resources/js'),
// //   }
// };
config.resolve.extensions = ['.tsx', '.ts', '.mjs', '.js', '.jsx', '.vue', '.json', '.wasm'];

// config.resolve = {
//   // vue: 'vue/dist/vue.js'
//   alias: {
//     vue: 'vue/dist/vue.js'
//   }
// }

/*
|--------------------------------------------------------------------------
| Export config
|--------------------------------------------------------------------------
|
| Export config for webpack to do its job
|
*/
module.exports = config;
