var gulp = require('gulp'),
	path = require('path'),
	tsc = require('../build/gulp/tsc');

var ROOT_FOLDER = __dirname;

function globPattern(workingDir) {
	return [
		workingDir + '/**/*.ts',
		path.join(ROOT_FOLDER, '../client/vs/monaco.d.ts'),
		path.join(ROOT_FOLDER, '../client/typings/mocha.d.ts'),
		path.join(ROOT_FOLDER, 'declares.d.ts'),
		path.join(ROOT_FOLDER, 'node.d.ts'),
		'!**/lib/lib*.d.ts',
		path.join(ROOT_FOLDER, 'lib.core.d.ts'),
	];
}

/**
 * Register two gulp pair tasks, one for compile and one for compile-watch and return their names.
 * @param opts Options. {`taskSuffix`, `dir`}
 * @return The names of the two tasks {compile, watch}
 */
var registerTasks = exports.registerTasks = function (opts) {
	var workingDir = path.resolve(path.join(ROOT_FOLDER, opts.dir));
	var glob = globPattern(workingDir);

	// create and keep compiler
	var compiler = tsc.create(glob, {
		noLib: true,
		target: 'es5',
		module: 'amd',
		declaration: false,
		verbose: true,
		gulpSrcOpts: {
			base: workingDir
		}
	});

	var compileTaskName = 'compile' + (opts.taskSuffix || '');
	var watchTaskName = 'compile-watch' + (opts.taskSuffix || '');

	// e.g. compile-vs.language.typescript
	gulp.task(compileTaskName, compiler.getFullCompileTask());
	gulp.task(watchTaskName, [compileTaskName], compiler.getWatchCompileTask());

	return {
		compile: compileTaskName,
		watch: watchTaskName
	};
};

var shouldRegisterGulpTasks = !process.env['DONT_REGISTER_GULP_TASKS'];

if (shouldRegisterGulpTasks) {

	registerTasks({
		dir: extractDirArg()
	});

	function extractDirArg() {
		for (var i = 0; i < process.argv.length; i++) {
			if (process.argv[i] === '--dir') {
				if (i + 1 < process.argv.length) {
					return process.argv[i + 1];
				}
			}
		}
		return '.';
	}
}

