'use strict';

const gulp = require('gulp');
const less = require('gulp-less');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const rename = require('gulp-rename');
var browserSync = require('browser-sync').create();

// ============================================
// LESS Tasks
// ============================================

function buildLess() {
    return gulp.src('./less/vermine2047.less')
        .pipe(less().on('error', function(err) {
            console.error('LESS compilation error:', err.message);
            this.emit('end');
        }))
        .pipe(autoprefixer({
            overrideBrowserslist: ['> 1%', 'last 2 versions', 'Firefox ESR'],
            cascade: false
        }))
        .pipe(cleanCSS({ compatibility: 'ie11' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('./css'))
        .pipe(browserSync.stream());
}

// Build LESS without minification (for debugging)
function buildLessDev() {
    return gulp.src('./less/vermine2047.less')
        .pipe(less().on('error', function(err) {
            console.error('LESS compilation error:', err.message);
            this.emit('end');
        }))
        .pipe(autoprefixer({
            overrideBrowserslist: ['> 1%', 'last 2 versions', 'Firefox ESR'],
            cascade: false
        }))
        .pipe(rename({ suffix: '.dev' }))
        .pipe(gulp.dest('./css'))
        .pipe(browserSync.stream());
}

function watchLess() {
    gulp.watch(['./less/**/*.less', './less/*.less'], buildLess);
}

function reloadTemplatesHTML() {
    return browserSync.reload("templates/**/*.html");
}

function reloadTemplatesHBS() {
    return browserSync.reload("templates/**/*.hbs");
}

// ============================================
// Exports
// ============================================

exports.buildLess = buildLess;
exports.buildLessDev = buildLessDev;
exports.buildCSS = gulp.series(buildLess);
exports.buildAllCSS = gulp.series(buildLess, buildLessDev);
exports.watch = function () {
    browserSync.init({
        server: false,
        proxy: {
            target: "https://localhost:30000/",
            ws: true,
        }
    });
    
    // Watch templates
    gulp.watch("./templates/**/*.html").on('change', reloadTemplatesHTML);
    gulp.watch("./templates/**/*.hbs").on('change', reloadTemplatesHBS);
    
    // Watch LESS files
    gulp.watch(['./less/**/*.less', './less/*.less'], buildLess);
};

exports.default = buildLess;
