var gulp = require('gulp');
var browserify = require('browserify');
var literalify = require('literalify');
var source = require("vinyl-source-stream");
var underscore = require('underscore');
var react = require('gulp-react');
var plumber = require('gulp-plumber');
var less = require('gulp-less');
var libMap = {
'jquery': 'window.$',
'underscore': 'window._',
'react': 'window.React',
'backbone': 'window.Backbone',
'director': 'window.Router'
};
var literalifyConf = literalify.configure(libMap);
var browserifyConf = {
basedir: '.'
};
var reactFiles = ['view1', 'todo', 'view2', 'view3', 'index'];
var backboneFiles = ['todo', 'todos'];
var libFiles = ['backbone', 'director', 'jquery', 'react', 'underscore'];
var reactJsFiles = underscore.map(reactFiles, function(file){return './client/views/' + file + '.js';});
var reactJsxFiles = underscore.map(reactFiles, function(file){return './client/views/' + file + '.jsx';});
var backboneJsFiles = underscore.map(backboneFiles, function(file){return './client/models/' + file + '.js';});
var libJsFiles = underscore.map(libFiles, function(file){return './client/libs/' + file + '.js';});
var jsDestPath = './public/javascript/';
gulp.task('browserify-expose', function(){
var b = browserify(browserifyConf);
b.transform(literalifyConf);
underscore.each(reactFiles, function(file){
var moduleName = file + ".js";
var modulePath = './client/views/' + moduleName;
b.require(modulePath, {expose: 'views/' + file});
b.add(modulePath);
});
underscore.each(backboneFiles, function(file){
var moduleName = file + ".js";
var modulePath = './client/models/' + moduleName;
b.require(modulePath, {expose: 'models/' + file});
b.add(modulePath);
});
underscore.each(libFiles, function(file){
var moduleName = file + ".js";
var modulePath = './client/libs/' + moduleName;
b.require(modulePath, {expose: 'libs/' + file});
b.add(modulePath);
});
b.add('./client/main.js');
b.bundle().pipe(source('bundle.js')).pipe(gulp.dest(jsDestPath));
});
gulp.task('move-client-files', function(){
gulp.src('./client/main.js').
pipe(gulp.dest(jsDestPath));
});
gulp.task('transform-jsx', function(){
gulp.src(reactJsxFiles)
.pipe(plumber())
.pipe(react())
.pipe(gulp.dest('./client/views/'));
});
gulp.task('transform-less', function(){
gulp.src('./public/stylesheet/*.less')
.pipe(plumber())
.pipe(less())
.pipe(gulp.dest('./public/stylesheet/'));
});
gulp.task('watch', function(){
gulp.watch(reactJsxFiles, ['transform-jsx']);
gulp.watch(reactJsFiles, ['browserify-expose']);
gulp.watch(backboneJsFiles, ['browserify-expose']);
gulp.watch('./client/main.js', ['browserify-expose']);
gulp.watch('./public/stylesheet/*.less', ['transform-less']);
});