var gulp = require('gulp');
var watch = require('gulp-watch');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var stripDebug = require('gulp-strip-debug');
var optimizejs = require('gulp-optimize-js');
var eventStream = require('event-stream');
var cleanCSS = require('gulp-clean-css');

var defaultTaks = function(files, type) {
	return (e) => { gulp.src(files)
		.pipe(gulp.dest('./dist/' + type + '/'));
	}
}

var libraries = ['lib/**/*.js'];
var scripts = ['src/**/*.js', 'shaders/**/*.js'];
var styles = ['css/**/*.css'];


// watch over src srcipts changes
gulp.task('default', function() {
	return eventStream.concat(
		watch(scripts, {ignoreInitial: false, verbose: true}, defaultTaks(scripts, 'js')),
		watch(libraries, {ignoreInitial: false, verbose: true}, defaultTaks(libraries, 'libs')),
		watch(styles, {ignoreInitial: false, verbose: true}, defaultTaks(styles, 'css'))
	);
});

// compile and minimalize both libraries and src scripts into separate outputs
gulp.task('production', function() {
	return eventStream.concat(
		gulp.src(libraries)
			.pipe(optimizejs())
			.pipe(stripDebug())
			.pipe(uglify())
			.pipe(gulp.dest('./dist/libs/')),
		gulp.src(scripts)
			.pipe(optimizejs())
			.pipe(stripDebug())
			.pipe(uglify())
			.pipe(gulp.dest('./dist/js/')),
		gulp.src(styles)
			.pipe(cleanCSS({compatibility: 'ie9'}))
			.pipe(gulp.dest('./dist/css/'))
	);
});
