
/*	========================================================================
 *
 *	GULPFILE by PG
 *
 *	------------------------------------------------------------------------
 *	AVAILABLE TASKS:
 *
 *	clean-dist
 *		Removes all content from 'dist' directory
 *
 *	css
 *		Compiles all SASS files from 'assets' and moves results to 'dist'
 *
 *	js
 *		Uglifies and concatenates all JS files from 'assets'
 *		and moves results to 'dist'.
 *
 *	images
 *		Copies all images from 'assets' to 'dist'
 *
 *	fonts
 *		Copies all fonts from 'assets' to 'dist'
 *
 *	default
 *		Runs tasks: clean-dist, js, css, images, fonts
 *
 *	watch
 *		Enters watch mode. Monitors changes in JS, CSS, Images
 *		and Fonts assets.
 *
 *	======================================================================== */


'use strict';


/*	============================================================================
 *	CONFIGURATION
 *	============================================================================ */

var

// Include gulp
	gulp		= require('gulp'),

// Include plugins
	del				= require('del'),
	runSequence		= require('run-sequence'),
	rename			= require('gulp-rename'),
	uglify			= require('gulp-uglify'),
	sass			= require('gulp-sass'),
	concat			= require('gulp-concat'),
	gutil			= require('gulp-util'),
	autoprefixer 	= require('gulp-autoprefixer'),
	sourcemaps 		= require('gulp-sourcemaps'),
	browserSync 	= require('browser-sync').create(),
	notify 			= require('gulp-notify'),
	environments	= require('gulp-environments'),

	development		= environments.development,
	production		= environments.production,

// Node.js functions
	fs				= require('fs'),

// Include configuration
	config			= require('./gulpconfig.js')();

// If local configuration exists include it
if (fs.existsSync('./gulpconfig-local.js')) {
	var localConfig = require('./gulpconfig-local.js')();

	// Overwrite global configuration by local variables
	for (var key in localConfig) {
		if (localConfig.hasOwnProperty(key)) {
			config[key] = localConfig[key];
		}
	}
}

// Report error
var reportError = function (error) {
	var lineNumber = (error.lineNumber) ? 'LINE ' + error.lineNumber + ' -- ' : '';

	if (config.errorHandlerNotify == true) {
		notify({
			title: 'Task Failed [' + error.plugin + ']',
			message: lineNumber + 'See console.',
			sound: config.errorHandlerNotifySound
		}).write(error);
	}

	if (config.errorHandlerBeep == true) {
		gutil.beep();
	}

	var report = '';
	var chalk = gutil.colors.white.bgRed;

	report += chalk('TASK:') + ' [' + error.plugin + ']\n';
	report += chalk('PROB:') + ' ' + error.message + '\n';
	if (error.lineNumber) { report += chalk('LINE:') + ' ' + error.lineNumber + '\n'; }
	if (error.fileName)   { report += chalk('FILE:') + ' ' + error.fileName + '\n'; }

	console.error(report);

	// Inspect the error object
	//console.log(error);

	this.emit('end');
};


/*	============================================================================
 *	TASKS
 *	============================================================================ */


/*	----------------------------------------------------------------------------
 *	Task: DELETE DIST
 */

gulp.task('clean-dist', function() {
	return del(config.basePaths.dist);
});


/*	----------------------------------------------------------------------------
 *	Task: CSS
 */

gulp.task('css', function() {

	return gulp.src([
			config.basePaths.assets + config.paths.assets.styles + '*.scss'
		])

		.pipe(development(sourcemaps.init()))
		.pipe(sass().on('error', reportError))
		.pipe(autoprefixer({
			browsers: config.compatibility
		}).on('error', reportError))
		.pipe(development(sourcemaps.write(undefined, { sourceRoot: null })))
		.pipe(production(sass({outputStyle: 'compressed'}).on('error', reportError)))
		.pipe(rename({suffix: '.min'}))
		.pipe(gulp.dest(config.basePaths.dist + config.paths.dist.styles))
		.pipe(browserSync.stream());
});


/*	----------------------------------------------------------------------------
 *	Task: JS
 */

var distJSDir	= config.basePaths.dist + config.paths.dist.scripts,
	report = '',
	chalk = gutil.colors.white.bgBlue;

// Merge all files together
gulp.task('js-saveJSConcatenated', function (error) {

	if (config.saveJSConcatenated == true) {

		if (config.jsFiles.front) {

			return gulp.src(
				config.jsFiles.front
			)
				.pipe(development(sourcemaps.init()))
				.pipe(concat({path: 'scripts.js'}).on('error', reportError))
				.pipe(development(sourcemaps.write()))
				.pipe(rename({suffix: '.min'}))
				.pipe(gulp.dest(distJSDir))
				.pipe(browserSync.stream());

		} else {

			report += chalk('INFO:') + ' File not found';
			console.log(report);

		}
	}
});

// Saves all files separately
gulp.task('js-allFilesSeparately', function (error) {

	if (config.saveJSSeparately == true) {

		if (config.jsFiles.front) {

			return gulp.src(
				config.jsFiles.front
			)
				.pipe(production(uglify().on('error', reportError)))
				.pipe(rename({suffix: '.min'}))
				.pipe(gulp.dest(distJSDir))
				.pipe(browserSync.stream());

		} else {

			report += chalk('INFO:') + ' File not found';
			console.log(report);

		}
	}
});

// Saves panel admin files separately
gulp.task('js-adminFiles', function () {

	if (config.jsFiles.back) {

		return gulp.src(
			config.jsFiles.back
		)
			.pipe(production(uglify().on('error', reportError)))
			.pipe(rename({suffix: '.min'}))
			.pipe(gulp.dest(distJSDir))
			.pipe(browserSync.stream());

	} else {

		report += chalk('INFO:') + ' File not found';
		console.log(report);

	}
});

// If you want save some JS separately
gulp.task('js-separatedJSFiles', function () {

	if (config.jsFiles.separated) {

		return gulp.src(
			config.jsFiles.separated
		)
			.pipe(production(uglify().on('error', reportError)))
			.pipe(rename({suffix: '.min'}))
			.pipe(gulp.dest(distJSDir))
			.pipe(browserSync.stream());

	} else {

		report += chalk('INFO:') + ' File not found';
		console.log(report);

	}
});


gulp.task('js', ['js-adminFiles', 'js-separatedJSFiles', 'js-saveJSConcatenated', 'js-allFilesSeparately']);


/*	----------------------------------------------------------------------------
 *	Task: IMAGES
 */

gulp.task('images', function() {
	return gulp.src([
			config.basePaths.assets + config.paths.assets.images + '**/*.' + config.fileExtensions.images
		])
		.pipe(gulp.dest(config.basePaths.dist + config.paths.dist.images))
		.pipe(browserSync.stream());
});

/*	----------------------------------------------------------------------------
 *	Task: VIDEO
 */

gulp.task('video', function() {
	return gulp.src([
			config.basePaths.assets + config.paths.assets.video + '**/*.' + config.fileExtensions.video
		])
		.pipe(gulp.dest(config.basePaths.dist + config.paths.dist.video))
		.pipe(browserSync.stream());
});

/*	----------------------------------------------------------------------------
 *	Task: FONTS
 */

gulp.task('fonts', function() {
	return gulp.src([
			config.basePaths.assets + config.paths.assets.fonts + '**/*.' + config.fileExtensions.fonts
		])
		.pipe(gulp.dest(config.basePaths.dist + config.paths.dist.fonts))
		.pipe(browserSync.stream());
});


/*	----------------------------------------------------------------------------
 *	Task: DEFAULT
 */

gulp.task('default', function(callback) {
	runSequence(
		'clean-dist',
		['css', 'js', 'images', 'video', 'fonts'],
		callback
	);
});


/*	----------------------------------------------------------------------------
 *	Task: WATCH
 */

gulp.task('watch', ['css',  'js-adminFiles', 'js-separatedJSFiles', 'js-saveJSConcatenated', 'images', 'video', 'fonts'], function () {
	gulp.watch(
		[config.basePaths.assets + config.paths.assets.styles + '**/*.scss'],
		['css']
	);

	gulp.watch(
		[config.jsFiles.back],
		['js-adminFiles']
	);

	gulp.watch(
		[config.jsFiles.separated],
		['js-separatedJSFiles']
	);

	if (config.saveJSConcatenated == true) {

		gulp.watch(
			[config.jsFiles.front],
			['js-saveJSConcatenated']
		);

	}

	if (config.saveJSSeparately == true) {

		gulp.watch(
			[config.jsFiles.front],
			['js-allFilesSeparately']
		);

	}

	gulp.watch(
		[config.basePaths.assets + config.paths.assets.images + '**/*.' + config.fileExtensions.images],
		['images']
	);


	gulp.watch(
		[config.basePaths.assets + config.paths.assets.images + '**/*.' + config.fileExtensions.video],
		['video']
	);

	gulp.watch(
		[config.basePaths.assets + config.paths.assets.fonts + '**/*.' + config.fileExtensions.fonts],
		['fonts']
	);
});


/*	----------------------------------------------------------------------------
 *	Task: SERVE
 */

gulp.task('serve', ['watch'], function(callback) {

	browserSync.init({
		proxy: config.domain
	});

	gulp.watch([
		'**/*.' + config.fileExtensions.watched
	])
	.on('change', browserSync.reload);
});

/*	----------------------------------------------------------------------------
 *	Task: DELETE MAINTENANCE DIST
 */

gulp.task('clean-dist-maintenance', function() {
	return del(config.basePaths.dist_maintenance);
});


/*	----------------------------------------------------------------------------
 *	Task: MAINTENANCE CSS
 */

gulp.task('maintenance-css', function() {

	return gulp.src([
		config.basePaths.assets + config.paths.assets.styles + '/maintenance/maintenance.scss'
	])

	// Save uncompressed
		.pipe(sourcemaps.init())
		.pipe(sass().on('error', reportError))
		.pipe(autoprefixer({
			browsers: config.compatibility
		}).on('error', reportError))
		.pipe(rename({suffix: ".min"}))
		.pipe(sass({outputStyle: 'compressed'}).on('error', reportError))
		.pipe(gulp.dest(config.basePaths.dist_maintenance + config.paths.dist_maintenance.styles + '/'))
		.pipe(browserSync.stream());
});

/*	----------------------------------------------------------------------------
 *	Task: MAINTENANCE IMAGES
 */

gulp.task('maintenance-images', function() {
	return gulp.src([
			config.basePaths.assets + config.paths.assets.images + '/maintenance/*.' + config.fileExtensions.images
		])
		.pipe(gulp.dest(config.basePaths.dist_maintenance + config.paths.dist_maintenance.images + '/'))
		.pipe(browserSync.stream());
});

/*	----------------------------------------------------------------------------
 *	Task: MAINTENANCE FONTS
 */

gulp.task('maintenance-fonts', function() {
	return gulp.src([
			config.basePaths.assets + config.paths.assets.fonts + '**/*.' + config.fileExtensions.fonts
		])
		.pipe(gulp.dest(config.basePaths.dist_maintenance + config.paths.dist_maintenance.fonts))
		.pipe(browserSync.stream());
});

/*	----------------------------------------------------------------------------
 *	Task: MAINTENANCE
 */

gulp.task('maintenance', function(callback) {
	runSequence(
		['maintenance-css', 'maintenance-images', 'maintenance-fonts'],
		callback
	);
});
