const {src, dest} = require('gulp');
const Sourcemaps = require('gulp-sourcemaps');

const CleanCSS = require('gulp-clean-css');
const Less = require('gulp-less');
const Browser = require('browser-sync');
const AutoPrefixer = require('gulp-autoprefixer');

const Logger = require('gulp-util');


function build(cb) {
    Logger.log('Building LESS');

    let stream = src([
        global.config.path.styles.src + '/Less/theme.less'
        // global.config.path.styles.src + 'Less/ie11.scss'
    ]);

    if (process.env.NODE_ENV !== "production") {
        Logger.log('- with Sourcemaps');
        stream = stream.pipe(Sourcemaps.init())
    }

    stream = stream.pipe(Less());


    if (process.env.NODE_ENV === "production") {
        stream = stream.pipe(AutoPrefixer({
            browserlist: ['>1% in DE']
        })).pipe(CleanCSS({
                level: 2,
                format: 'none',
            }, function (details) {
                Logger.log(details.name + ': ' + (details.stats.originalSize / 1024).toFixed(2) + '/' + (details.stats.minifiedSize / 1024).toFixed(2) + ' KB' + ' (-' + (details.stats.efficiency * 100).toFixed(2) + '%)')
            }
        ));
    }

    if (process.env.NODE_ENV !== "production") {
        stream = stream.pipe(Sourcemaps.write())
    }

    stream = stream.pipe(dest(global.config.path.styles.dest));

    if (process.env.NODE_ENV !== "production") {
        stream = stream.pipe(Sourcemaps.write())
            .pipe(Browser.reload({stream: true}));
        Logger.log('- reloading Browsersync');
    }
    cb();
    //return stream;
}

exports.build = build;