import fs from 'fs';
import glob from 'glob';

export default function generateModuleStyles() {
    function readDirFiles(dir, array) {
        (glob.sync(dir) || []).forEach((f) => {
            f = f.replace(/[\\/]+/g, '/');
            if (f !== null) {
                array.push(f);
            }
        });

        return array;
    }

    function generate(id) {
        let file = 'assets/scss/modules.scss';

        // If 'id' contains path of the blocks.scss file, return
        if (id.includes(file)) return;

        // Generate blocks.scss file
        let data = '// This file is generated automatically when Vite is running or building.\n';

        let blocksScssFiles = [];
        readDirFiles('modules/**/**/*.scss', blocksScssFiles);

        blocksScssFiles.forEach((element) => {
            data += `@import '../../${element}';\n`;
        });

        // If data differs from the current blocks.scss file, write the new data to the file
        if (data !== fs.readFileSync(file, 'utf8')) {
            fs.writeFile(file, data, (err) => {
                if (err) throw err;
            });
        }
    }

    return {
        name: 'generate-modules-scss',

        watchChange(id, change) {
            generate(id);
        },

        buildStart(build) {
            generate(build.input);
        }
    };
}
