var gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    cleanCSS = require('gulp-clean-css'),
    sourcemaps = require('gulp-sourcemaps'),
    imagemin = require('gulp-imagemin'),
    minify = require('gulp-minify'),
    minifyInline = require('gulp-minify-inline'),
    lineec = require('gulp-line-ending-corrector'),
    htmlmin = require('gulp-htmlmin'),
    replace = require('gulp-replace'),
    del = require('del'),
    rename = require('gulp-rename'),
    browserSync = require('browser-sync').create();

//Get the environment from the gulp command line, options (dev, prod)
const optimizeBuild = ((process.env.BUILD_OPTIMIZE || '').trim().toLowerCase() === 'true'); //Default is false.
const outputDirectory = (process.env.BUILD_OUTPUT_DIR || 'dev');

console.log(`Optimize Build: ${optimizeBuild}`);
console.log(`Output Directory: ${outputDirectory}`);

function cleanOutputTask() {
    console.log("Cleaning up output directory..");
    return del([
        `${outputDirectory}/**/*`
    ]);
}

function htmlTask() {
    if (!optimizeBuild) {
        return gulp.src(['!src/_*.html', 'src/*.html', 'src/**/*.html'])
            .pipe(htmlmin({ caseSensitive: true, removeComments: true, conservativeCollapse: true, collapseWhitespace: true }))
            .pipe(minifyInline({ js: { mangle: false, compress: true } }))
            .pipe(lineec())
            .pipe(gulp.dest(`${outputDirectory}/`));
    } else {
        return gulp.src(['!src/_*.html', 'src/*.html', 'src/**/*.html'])
            .pipe(htmlmin({ caseSensitive: true, removeComments: true, conservativeCollapse: true, collapseWhitespace: true }))
            .pipe(minifyInline({ js: { mangle: false, compress: true } }))
            .pipe(lineec())
            .pipe(gulp.dest(`${outputDirectory}/`));
    }
}

function scssTask() {
    if (!optimizeBuild) {
        return gulp.src([
            'src/**/*.scss',
            'src/*.scss'])
            .pipe(sourcemaps.init({ loadMaps: true }))
            .pipe(sass({
                outputStyle: 'expanded'
            }).on('error', sass.logError))
            .pipe(autoprefixer('last 2 versions'))
            .pipe(cleanCSS())
            .pipe(sourcemaps.write())
            .pipe(lineec())
            .pipe(gulp.dest(`${outputDirectory}/`));
    } else {
        return gulp.src([
            'src/**/*.scss',
            'src/*.scss',
            '!src/_*.scss',
            '!src/**/_*.scss'])
            .pipe(sass({
                outputStyle: 'expanded'
            }).on('error', sass.logError))
            .pipe(autoprefixer('last 2 versions'))
            .pipe(cleanCSS())
            .pipe(lineec())
            .pipe(gulp.dest(`${outputDirectory}/`));
    }
}

function jsTask() {
    if (!optimizeBuild) {
        return gulp.src([
            'src/**/*.js',
            'src/*.js'])
            .pipe(sourcemaps.init({ loadMaps: true }))
            .pipe(sourcemaps.write())
            .pipe(lineec())
            .pipe(gulp.dest(`${outputDirectory}/`));
    } else {
        return gulp.src([
            'src/**/*.js',
            'src/*.js'])
            .pipe(minify({
                mangle: false,
                compress: true,
                noSource: true,
                ext: {
                    min: '.js'
                }
            }))
            .pipe(lineec())
            .pipe(gulp.dest(`${outputDirectory}/`));
    }
}

function fontsTask() {
    return gulp.src([
        'src/*.ttf',
        'src/**/*.ttf',
        'src/*.woff',
        'src/**/*.woff',
        'src/*.woff2',
        'src/**/*.woff2',
        'src/*.eot',
        'src/**/*.eot'])
        .pipe(rename({ dirname: '' }))
        .pipe(gulp.dest(`${outputDirectory}/`));
}

function watchTask() {
    console.log("Starting browserSync... hold on");

    browserSync.init({
        open: 'local',
        port: 8080,
        server: `${outputDirectory}/`,
    });

    //Watch for any site changes
    gulp.watch(['src/*.scss', 'src/**/*.scss'], gulp.series(scssTask)).on('change', browserSync.reload);;
    gulp.watch(['src/*.js', 'src/**/*.js'], gulp.series(jsTask)).on('change', browserSync.reload);;
    gulp.watch(['src/*.html', 'src/**/*.html'], gulp.series(htmlTask)).on('change', browserSync.reload);;

    return Promise.resolve();
}

//Site Tasks
exports.htmlTask = htmlTask;
exports.scssTask = scssTask;
exports.jsTask = jsTask;
exports.fontsTask = fontsTask;
exports.cleanOutputTask = cleanOutputTask;
exports.watchTask = watchTask;

var build = gulp.series(
    [
        cleanOutputTask,
        gulp.parallel(
            htmlTask,
            scssTask,
            jsTask,
            fontsTask
        )
    ]);

gulp.task('default', build);
gulp.task('run', watchTask);