/* vim: set filetype=javascript shiftwidth=4 tabstop=4 expandtab: */
"use strict";

var gulp = require("gulp");
var sass = require("gulp-sass");
var browserify = require("browserify");
var espowerify = require("espowerify");
var transform = require("vinyl-transform");
var exorcist = require("exorcist");

var argv = require("yargs").argv;

var isRelease = argv.release

var SRC_JS = "./script/main.js";
var SRC_CSS = "./style/main.scss";
var DIST_BUILD_DIR = "./build/";
var DIST_JS_MAP_FILE = DIST_BUILD_DIR + "main.js.map";

var SRC_TEST = "./test/manifest.js";
var DIST_TEST_DIR = "./powered-test/";


gulp.task("css", function() {
    var option = {
        errLogToConsole: true,
        // sourcemap
        sourceComments: isRelease ? "none" : "map",
        // "expanded" are not supported currently by libsass
        outputStyle: "expanded",
    };

    gulp.src(SRC_CSS)
        .pipe(sass(option))
        .pipe(gulp.dest(DIST_BUILD_DIR));
});

gulp.task("js", function() {
    var option = {
        insertGlobals: false,
        debug: isRelease ? false : true,
    };

    var browserifier = transform(function(filename){
        var b = browserify(option).add(filename)
        return b.bundle();
    });

    gulp.src(SRC_JS)
        .pipe(browserifier)
        .pipe(exorcister)
        .pipe(gulp.dest(DIST_BUILD_DIR));
});

gulp.task("espower", function() {
    var option = {
        insertGlobals : false,
        debug : true,
    };

    var browserifier = transform(function(filename){
        var b = browserify(option).add(filename)
                                  .transform(espowerify);
        return b.bundle();
    });

    gulp.src(SRC_TEST)
        .pipe(browserifier)
        .pipe(gulp.dest(DIST_TEST_DIR));
});

gulp.task("jstest", ["espower"], function() {});
gulp.task("build", ["css", "js"], function() {});

// Split sourcemap into the file.
var exorcister = transform(function(){
    return exorcist(DIST_JS_MAP_FILE);
});

@@ -297,17 +297,51 @@
 rcist%22);
+ // Split sourcemap into the file.
 %0A
-
 %0Avar arg
@@ -553,16 +553,74 @@
 js.map%22;
+%0Avar DIST_CSS_MAP_FILE = DIST_BUILD_DIR + %22main.scss.map%22;
 %0A%0Avar SR
@@ -942,24 +942,120 @@
 d%22,%0A    %7D;%0A%0A
+    var exorcister = transform(function()%7B%0A        return exorcist(DIST_CSS_MAP_FILE);%0A    %7D);%0A%0A
     gulp.src
@@ -1092,16 +1092,42 @@
 ption))%0A
+        .pipe(exorcister)%0A
         
@@ -1422,32 +1422,127 @@
 dle();%0A    %7D);%0A%0A
+    var exorcister = transform(function()%7B%0A        return exorcist(DIST_JS_MAP_FILE);%0A    %7D);%0A%0A
     gulp.src(SRC
@@ -2103,16 +2103,16 @@
 () %7B%7D);%0A
+
 gulp.tas
@@ -2157,121 +2157,4 @@
 %7D);%0A
-%0A// Split sourcemap into the file.%0Avar exorcister = transform(function()%7B%0A    return exorcist(DIST_JS_MAP_FILE);%0A%7D);%0A

Split css sourcemap into the separated file.