const gulp = require('gulp');
const purgecss = require('gulp-purgecss');
const merge = require('lodash/merge');

/*
 *  Extractor to be used by purgecss.
 *  More info here: https://www.purgecss.com/extractors
 */
class TailwindExtractor {
    static extract(content) {
        return content.match(/[A-z0-9-:/]+/g) || [];
    }
}

/*
 *  Default configuration for this task. Adjustments specific
 *  to the site package should be specified as overrrides in its
 *  gulpfile.
 */
const defaultConfig = {
    // Path glob for all stylesheets which should be purged.
    src: './Packages/Sites/Newland.CityTheme/Resources/Public/Stylesheets/*.css',

    // Path where purged stylesheets are placed (same directory as src).
    dist: './Packages/Sites/Newland.CityTheme/Resources/Public/Stylesheets',

    /*
     *  Options to be passed to purgecss.
     *  More infor here: https://www.npmjs.com/package/gulp-purgecss
     */
    purgeOptions: {
        content: [
            /*
             *  Specify the files (glob paths) to scan for class names.
             *  If a class name is found in any of these files, purge will
             *  not delete style definitions for this class.
             */
            './Packages/Plugins/Newland.AssetsNeos/Styles/vendor/**/*.scss',
            './Packages/Plugins/Newland.AssetsNeos/Styles/components-map/*.scss',
            './Packages/Application/Newland.NeosFiltering/**/*.html',
            './Packages/Application/Newland.NeosFiltering/**/*.fusion',
            './Sass/vendor/**/*.scss',
            './Sass/overrides/**/*.scss',
            './Packages/Sites/**/*.html',
            './Packages/Sites/**/*.fusion',
            './Packages/Sites/**/*.yaml',
            './Packages/Sites/Newland.CityTheme/Resources/Public/**/*.js',
            './Packages/Plugins/**/*.html',
            './Packages/Plugins/**/*.yaml',
            './Packages/Plugins/**/*.fusion',
            './Packages/Plugins/**/*.vue',
        ],
        extractors: [
            {
                extractor: TailwindExtractor,

                /*
                 *  Specify the file extensions to include when
                 *  scanning for class names.
                 */
                extensions: [ 'js', 'html', 'scss', 'md', 'yaml', 'fusion', 'vue' ],
            },
        ],
    },
};

module.exports = config => {
    const mergedConfig = config ? merge(defaultConfig, config) : defaultConfig;

    return gulp
        .src(mergedConfig.src)
        .pipe(purgecss(mergedConfig.purgeOptions))
        .pipe(gulp.dest(mergedConfig.dist));
};
