/***************
 * Ingredients *
 ***************/

const gulp        = require('gulp');
const browserSync = require('browser-sync');
const sass        = require('gulp-sass');
const prefix      = require('gulp-autoprefixer');
const csso        = require('gulp-csso');
// Jekyll
const cp          = require('child_process');
const jekyll      = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';


/************
 * Settings *
 ************/

let BS_BASE       = '_site';

let SASS_SRC      = '_sass/main.sass';
let SASS_DEST     = '_site/assets/css';

let WATCH_SASS    = '_sass/**/*.sass';
let WATCH_FILES   = [
                      'assets/**',
                      '*.html',
                      '_includes/**',
                      '_layouts/**'
                    ];


///////////////////////////
// Build the Jekyll Site //
///////////////////////////

gulp.task('jekyll-build', function(done) {
	return cp.spawn(jekyll, ['build'], {
			stdio: 'inherit'
		})
		.on('close', done);
});


//////////////////////////////////////////
// Rebuild Jekyll & Reload Browser-Sync //
//////////////////////////////////////////

gulp.task('jekyll-rebuild', ['jekyll-build'], function() {
	browserSync.reload();
});


///////////////////////////////////////////////////
// Build Jekyll & Launch the Browser-Sync server //
///////////////////////////////////////////////////

gulp.task('browser-sync', ['sass', 'jekyll-build'], function() {
	browserSync.init({
		server: {
			baseDir: BS_BASE
		},
		notify: false
	});
});


/////////////////////////////////////////////////////////////////
// Compile, autoprefix, minify sass & Inject with Browser-Sync //
/////////////////////////////////////////////////////////////////

gulp.task('sass', function() {
	return gulp.src(SASS_SRC)
		.pipe(sass().on('error', sass.logError))
		.pipe(prefix({
			browsers: ['last 2 versions'],
			cascade: false
		}))
		.pipe(csso())
		.pipe(gulp.dest(SASS_DEST))
		.pipe(browserSync.stream());
});


///////////////////////////////////////////
// Watch sass & Recompile + Inject       //
// Watch files & Rebuild Jekyll + Reload //
///////////////////////////////////////////

gulp.task('watch', function() {
	gulp.watch(WATCH_SASS, {cwd: './'}, ['sass']);
	gulp.watch(WATCH_FILES, {cwd: './'}, ['jekyll-rebuild']);
});


/////////////////////////
// Default 'gulp' task //
/////////////////////////

gulp.task('default', ['browser-sync', 'watch']);
