const { parallel, series } = require('gulp');
const fs = require('fs');
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();

const minify = require('@node-minify/core');
const cleanCSS = require('@node-minify/clean-css');

const PROJECT_NAME = resolveProjectName();
const PATH_TO_DPL = resolvePathDpl();

function compilaSass() {
    return gulp.src([`src/${PROJECT_NAME}/*.scss`])
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(PATH_TO_DPL ? PATH_TO_DPL : `dist/${PROJECT_NAME}/`))
        .pipe(browserSync.stream());
}

function copyImages() {
    return gulp.src(`src/${PROJECT_NAME}/images/**/*`)
        .pipe(gulp.dest((PATH_TO_DPL ? PATH_TO_DPL : `dist/${PROJECT_NAME}`) + "/images"));
}

function browser() {
    browserSync.init({
        server:{
            baseDir: "./dist/"
        }
    })
}

function watch() {
    gulp.watch(`src/${PROJECT_NAME}/**/*.scss`, { ignoreInitial: false }, compilaSass);
    gulp.watch(`src/${PROJECT_NAME}/images/**/*.*`, { ignoreInitial: false }, copyImages);
    gulp.watch('dist/**/*').on('change', browserSync.reload);
}

function minifyCss() {
    if (fs.existsSync('dist/default/ez-themed.min.css')) {
        fs.unlinkSync('dist/default/ez-themed.min.css');
    }
    return minify({
        compressor: cleanCSS,
        input: ['dist/default/**/*.css', '!dist/default/icons/fonts/ez-icons.css'],
        output: 'dist/default/$1.min.css',
    });
}

function resolveProjectName() {
    var idx = process.argv.indexOf("--pname");
    if (idx > -1) {
        return process.argv[idx + 1];
    }
    return 'default';
}

function resolvePathDpl() {
    var idx = process.argv.indexOf("--dpl");
    if (idx > -1) {
        return process.argv[idx + 1];
    }
    return undefined;
}

function copyCommons(){
    return gulp.src(`src/commons/**/*`)
    .pipe(gulp.dest((PATH_TO_DPL ? PATH_TO_DPL : `dist/commons`)));
}

function copyFonts(){
    return gulp.src([`src/${PROJECT_NAME}/fonts/**/*`, `!src/${PROJECT_NAME}/fonts/**/*.scss`])
    .pipe(gulp.dest((PATH_TO_DPL ? PATH_TO_DPL : `dist/${PROJECT_NAME}/fonts`)));
}


gulp.task('browser-sync', browser);
gulp.task('watch', watch);
gulp.task('compila-sass', compilaSass);
gulp.task('copy-images', copyImages);
gulp.task('minify-css', minifyCss);
gulp.task('copy-commons', copyCommons);
gulp.task('copy-fonts', copyFonts);
gulp.task('default', parallel('watch', 'browser-sync'));
gulp.task('build', series(parallel('compila-sass', 'copy-images', 'copy-commons', 'copy-fonts'), 'minify-css'));