// see https://github.com/tugberkugurlu/gulp-bootswatch-sample/

var gulp = require('gulp'),
    changed = require('gulp-changed'),
    concat = require('gulp-concat'),
    debug = require('gulp-debug'),
    foreach = require('gulp-foreach'),
    gulpif = require('gulp-if'),
    gutil = require('gulp-util'),
    imagemin = require('gulp-imagemin'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifycss = require('gulp-minify-css'),
    minifyhtml = require('gulp-minify-html'),
    order = require('gulp-order'),
    rename = require('gulp-rename'),
    stripdebug = require('gulp-strip-debug'),
    uglify = require('gulp-uglify'),
    path = require('path'),
    merge = require('merge-stream'),
    del = require('del');

var bootswatch_theme = 'superhero';

var production = false;

gulp.task('default', [], function() {
    gulp.start('styles', 'scripts', 'images', 'jade');
});

gulp.task('all', [], function() {
    gulp.start('fonts', 'styles', 'scripts', 'images', 'jade');
});

gulp.task('rebuild', ['clean'], function() {
    gulp.start('all');
});

gulp.task('clean', function(cb) {
    del(['./build/assets/css', './build/assets/js', './build/assets/less', './build/assets/img', './build/assets/fonts', './build/*.html'], cb)
});

gulp.task('fonts', function() {
    
    var fileList = [
        './bower_components/bootstrap/dist/fonts/*', 
        './bower_components/fontawesome/fonts/*'
    ];

    var dst = './build/assets/fonts';
    
    return gulp.src(fileList)
        .pipe(changed(dst))
        .pipe(gulp.dest(dst));
});

gulp.task('styles', function() {
    
    var baseContent = 
        '@import "./bower_components/bootstrap/less/bootstrap.less";' + 
        '@import "./bower_components/bootswatch/' + bootswatch_theme + '/variables.less";' + 
        '@import "./bower_components/bootswatch/' + bootswatch_theme + '/bootswatch.less";' + 
        '@import "./bower_components/bootstrap/less/utilities.less";';
    
    var isBootswatchFile = function(file) {
        var suffix = 'bootswatch.less';
        return file.path.indexOf(suffix, file.path.length - suffix.length) !== -1;
    }
    
    var isBootstrapFile = function(file) {
        var suffix = 'bootstrap-',
            fileName = path.basename(file.path);
        
        return fileName.indexOf(suffix) == 0;
    }
    
    var fileList = [
        './bower_components/bootswatch/' + bootswatch_theme + '/bootswatch.less', 
        './bower_components/fontawesome/css/font-awesome.css',
        './src/css/style.less'
    ];

    var dst = './build/assets/css';
    var bootswatch_dst = 'bootswatch.css';
    
    return gulp.src(fileList)
        .pipe(changed(dst, {extension: '.css', destination: function(file){
            if (isBootswatchFile(file)) {
                return 'bootswatch.css';
            } else {
                return file;
            }
        }}))
        //.pipe(changed(dst, { destination: 'style.css' }))
        .pipe(gulpif(isBootswatchFile, foreach(function(stream, file) {
            var themeName = path.basename(path.dirname(file.path)),
                content = replaceAll(baseContent, bootswatch_theme, themeName),
                file = string_src('bootstrap-' +  themeName + '.less', content);

            return file;
        })))
        .pipe(less())
        .pipe(gulpif(isBootstrapFile, foreach(function(stream, file) {
            var fileName = path.basename(file.path),
                themeName = fileName.substring(fileName.indexOf('-') + 1, fileName.indexOf('.'));
            
            // http://stackoverflow.com/questions/21719833/gulp-how-to-add-src-files-in-the-middle-of-a-pipe
            // https://github.com/gulpjs/gulp/blob/master/docs/recipes/using-multiple-sources-in-one-task.md
            return merge(stream, gulp.src(['./build/assets/css/font-awesome.css', './build/assets/css/main.css']))
                .pipe(concat('bootswatch.css'))
                .pipe(gulp.dest(dst))
                .pipe(rename({suffix: '.min'}))
                .pipe(minifycss());
        })))
        .pipe(minifycss())
        .pipe(gulp.dest(dst));
});

gulp.task('scripts', function(){
    var fileList = [
        './bower_components/jquery/dist/jquery.min.js',
        './bower_components/bootstrap/dist/js/bootstrap.min.js',
        './bower_components/jquery-cookie/jquery.cookie.js'
    ];

    var dst = './build/assets/js';

    gulp.src(fileList)
        .pipe(changed(dst, {destination: 'script.js'}))
        .pipe(concat('script.js'))
        .pipe(stripdebug())
        .pipe(uglify())
        .pipe(gulp.dest(dst));

    var src = './src/js/*.js';

    gulp.src(src)
        .pipe(changed(dst))
        .pipe(gulpif(production, stripdebug()))
        .pipe(uglify())
        .pipe(gulp.dest(dst));
});

gulp.task('images', function(){
    var src = './src/img/**/*',
        dst = './build/img';

    gulp.src(src)
        .pipe(changed(dst))
        .pipe(imagemin())
        .pipe(gulp.dest(dst));
});

gulp.task('jade', function(){
    var src = './src/*.jade',
        dst = './build';

    gulp.src(src)
        .pipe(changed(dst, {extension: 'html'}))
        .pipe(jade())
        .pipe(minifyhtml())
        .pipe(gulp.dest(dst));
});

// http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript
function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function replaceAll(string, find, replace) {
  return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function string_src(filename, string) {
  var src = require('stream').Readable({ objectMode: true })
  src._read = function () {
    this.push(new gutil.File({ cwd: "", base: "", path: filename, contents: new Buffer(string) }))
    this.push(null)
  }
  return src
}