const fs = require('fs');
const path = require('path');
const cssnano = require('cssnano');

const logger = global.yoho.logger;
const css = {};

module.exports = (file) => {
    const isNotDev = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test';

    if (css[file] && isNotDev) {
        return Promise.resolve(css[file]);
    }

    const cssPath = path.join(__dirname, 'css', file);
    const cssfile = fs.readFileSync(cssPath).toString();

    logger.info(`cssnano process ${cssPath}`);
    return cssnano.process(cssfile, {
        safe: true,
        autoprefixer: {
            add: true,
            browsers: ['> 1%', 'android >=4', 'ios >=8']
        }
    }).then(function(result) {
        if (result && result.css) {
            css[file] = result.css;
            return css[file];
        }
        return '';
    }).catch(err => {
        logger.error(err);
        return '';
    });
};