const gulp = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const coffee = require('gulp-coffee');
const sourcemaps = require('gulp-sourcemaps');
const plumber = require('gulp-plumber');

// Compile .sass files to compressed CSS
function compileSass() {
  return gulp.src('assets/styles/**/*.sass')
    .pipe(plumber())
    .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))
    .pipe(gulp.dest('public/css'));
}

// Compile .coffee files to JavaScript with source maps
function compileCoffee() {
  return gulp.src('assets/scripts/**/*.coffee', { sourcemaps: true })
    .pipe(plumber())
    .pipe(coffee({ bare: true }))
    .pipe(gulp.dest('public/js', { sourcemaps: '.' }));
}

// Copy image files to public/img/
function copyImages() {
  return gulp.src('assets/img/**/*', {encoding: false})
    .pipe(gulp.dest('public/img/'));
}

// Watch files for changes
function watchFiles(cb) {
  gulp.watch('assets/styles/**/*.sass', compileSass);
  gulp.watch('assets/scripts/**/*.coffee', compileCoffee);
  gulp.watch('assets/img/**/*', copyImages)
  cb();
}

// Chain all asset builds together
function buildAssets() {
  return gulp.parallel(compileSass, compileCoffee, copyImages);
}

// Perform initial build then watch
function buildAndWatch() {
  return gulp.series(
    buildAssets(),
    watchFiles
  );
}

// one-time build
exports.build = buildAssets();

// start builds with file watching
exports.watch = buildAndWatch();

// Define default task (defaults to watch)
exports.default = exports.watch;
