var gulp = require("gulp"),
	concat = require("gulp-concat"),
	karma = require("karma").server,
	mocha = require("gulp-mocha"),
	nodemon = require("gulp-nodemon"),
	notify = require("gulp-notify"),
	size = require("gulp-filesize"),
	sourcemaps = require("gulp-sourcemaps"),
	uglify = require("gulp-uglify"),
	typescript = require("gulp-tsc");

gulp.task("default", function () {
	gulp.start("server");
	gulp.start("watch");
});

gulp.task("watch", function () {
	gulp.watch("assets/js/**/*.ts", ["typescript-client"]);
	gulp.watch("assets/dist/js/*.js", ["test-client", "client"]);
});

gulp.task("client", function () {
	gulp.src([
		"bower_components/jquery/dist/jquery.min.js",
		"bower_components/lodash/lodash.min.js",
		"bower_components/rxjs/dist/rx.all.min.js",
		"bower_components/Rx-jQuery/rx.jquery.js",
		"assets/dist/js/lib.js"
	])
		.pipe(sourcemaps.init())
		.pipe(concat("app.js"))
		.pipe(sourcemaps.write())
		.pipe(gulp.dest("assets/dist/js"))
		.pipe(notify("app.js successfully compiled"))
		.pipe(size());
});

gulp.task("server", function () {
	nodemon({
		script: "app/boot.js",
		ext: "ts html",
		ignore: ["assets/**/*", "README"],
		env: {"NODE_ENV": "development"},
		tasks: ["typescript", "test"]
	}).on("restart", function () {
		//console.log("Server restarted!");
	});
});

gulp.task("typescript-client", function () {
	tsc("assets/js", "assets/dist/js", "client");
	tscClientTest("assets/js");
});

gulp.task("typescript", function () {
	tsc("app", "app", "server");
});

gulp.task("test-client", function (done) {
	karma.start({
		configFile: process.cwd() + "/assets/js/test/karma.conf.js"
	}, done);
});

gulp.task("test", function () {
	return gulp.src("app/**/*.spec.js", {read: false})
		.pipe(mocha({reporter: "list"}));
});

function tsc(path, out, type) {
	var src = gulp.src([
		path + "/**/*.ts",

		// Ignore specs and typings
		"!" + path + "/**/*.spec.ts",
		"!" + path + "/typings/**/*"
	], {base: path});

	var dest;

	if (type == "client") {
		dest = src.pipe(typescript({
			target: "ES5",
			sortOutput: true,
			sourceMap: false,
			removeComments: true
		}))
			.pipe(concat("lib.js"));
			//.pipe(uglify());
	} else {
		dest = src.pipe(typescript(
			{
				target: "ES5",
				sourcemap: true,
				declarationFiles: true,
				removeComments: true
			}
		));
	}

	dest
		.pipe(gulp.dest(out))
		.pipe(notify(path + " tsc compiled into JavaScript"))
		.pipe(size());
}

function 
(path) {
	var src = gulp.src([
		path + "/**/*.spec.ts"
	], {base: path});

	src.pipe(typescript({
		target: "ES5",
		sortOutput: true,
		sourceMap: false,
		removeComments: true
	}))
		.pipe(concat("all.js"))
		.pipe(gulp.dest(path + "/test"))
		.pipe(notify(path + " tscTest compiled into JavaScript"))
		.pipe(size());
}
tscClientTest