var path = require('path');
var fs = require('fs');
var uglifycss = require('uglifycss');
const { getAppConfig, pathResolve } = require('./utils.js');
const appConfig = getAppConfig();

const compressCss = (dir) => {
    fs.readdir(dir, (err, files) => {
        if (!err) {
            files.forEach(function (file) {
                const filePath = path.join(dir, file)
                fs.stat(filePath, (err, stats) => {
                    if (!err) {
                        if (stats.isDirectory()) {
                            compressCss(filePath)
                        } else if (stats.isFile() && /\.css$/i.test(file)) {
                            const uglifiedCss = uglifycss.processFiles(
                                [filePath],
                                {
                                    cuteComments: true
                                }
                            );
                            fs.writeFile(filePath, uglifiedCss, { encoding: 'utf-8' }, (err) => { });
                        }
                    }
                });
            })
        }
    })
};

module.exports = (...paths) => {
    if (paths.length > 0) {
        compressCss(pathResolve(...paths));
    } else {
        compressCss(pathResolve(appConfig.distPath));
    }
};