import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import html from '@rollup/plugin-html';
import { glob } from 'glob';

/**
 * Get Files from a directory
 * @param {string} query
 * @returns array
 */
function GetFilesArray(query) {
    return glob.sync(query);
}
/**
 * Js Files
 */
// Processing Modules JS Files
const ModulesJsFiles = GetFilesArray('modules/Admin/Resources/**/*.js');


/**
 * Scss Files
 */
// Processing Libs Scss & Css Files
const ModulesScssFiles = GetFilesArray('modules/Admin/Resources/**/!(_)*.scss');
const ModulesScsFiles = GetFilesArray('modules/Admin/Resources/**/*.css');



// Processing Website Vendor JS Files
const WebVendorJsFiles = GetFilesArray('resources/assets/vendor/**/*.js');

// Processing Website Libs JS Files
const WebJsFiles = GetFilesArray('resources/js/**/*.js');

// Processing Website Core, Themes, Libs Scss & Css Files
const WebVendorScsFiles = GetFilesArray('resources/assets/vendor/**/*.css');
const WebScsFiles = GetFilesArray('resources/css/**/*.css');

// Processing Window Assignment for Libs like jKanban, pdfMake
function libsWindowAssignment() {
    return {
        name: 'libsWindowAssignment',

        transform(src, id) {
            if (id.includes('jkanban.js')) {
                return src.replace('this.jKanban', 'window.jKanban');
            } else if (id.includes('vfs_fonts')) {
                return src.replaceAll('this.pdfMake', 'window.pdfMake');
            }
        }
    };
}

export default defineConfig({
    plugins: [
        laravel({
            input: [
                ...ModulesJsFiles,
                ...ModulesScssFiles,
                ...ModulesScsFiles,
                ...WebVendorJsFiles,
                ...WebJsFiles,
                ...WebVendorScsFiles,
                ...WebScsFiles
            ],
            refresh: ['resources/**', 'routes/**', 'app/**', 'modules/**']
        }),
        html(),
        libsWindowAssignment()
    ],
    resolve: {
        alias: {
            '@admin': '/Modules/Admin/Resources'
        }
    },
    server: {
        watch: {
            //ignored: ['!**/modules/**'],
            usePolling: true,
            interval: 300
        }
    }
});
