"use strict";

var gulp    = require("gulp");
var plugins = require("gulp-load-plugins")();

var paths = {
    lint: ["./gulpfile.js", "./lib/**/*.js", "./test/**/*.js"],
    watch: ["./gulpfile.js", "./lib/**", "./test/**/*.js", "!test/{temp,temp/**}"],
    tests: ["./test/**/*spec.js", "!test/{temp,temp/**}"],
    source: ["./lib/*.js"]
};

gulp.task("lint", function () {
    return gulp.src(paths.lint)
        .pipe(plugins.plumber())
        .pipe(plugins.eslint())
        .pipe(plugins.eslint.format())
        .pipe(plugins.eslint.failOnError());
});

gulp.task("istanbul", function (cb) {
    gulp.src(paths.source)
        .pipe(plugins.plumber())
        .pipe(plugins.istanbul()) // Covering files
        .pipe(plugins.istanbul.hookRequire()) // Force `require` to return covered files
        .on("finish", function () {
            gulp.src(paths.tests)
                .pipe(plugins.plumber())
                .pipe(plugins.mocha({
                    reporter: "spec",
                    ui: "bdd",
                    growl: true,
                    files: "./test/config/chai.js"}))
                .pipe(plugins.istanbul.writeReports()) // Creating the reports after tests runned
                .on("finish", function() {
                    process.chdir(__dirname);
                    cb();
                });
        });
});

gulp.task("mocha", function () {
    return gulp.src(paths.tests)
        .pipe(plugins.plumber())
        .pipe(plugins.mocha({
            reporter: "spec",
            ui: "bdd",
            growl: true,
            files: "./test/config/chai.js"
    }));
});

gulp.task("bump", ["test"], function () {
    var bumpType = plugins.util.env.type || "patch"; // major.minor.patch

    return gulp.src(["./package.json"])
        .pipe(plugins.bump({ type: bumpType }))
        .pipe(gulp.dest("./"));
});

gulp.task("watch", function () {
    plugins.watch(paths.watch, function () {
        gulp.start(["test"]);
    });
});

gulp.task("jsdoc", function () {
    return gulp.src(paths.source)
        .pipe(plugins.plumber())
        .pipe(plugins.jsdoc("./documentation-output"));
});

gulp.task("test", ["lint", "istanbul"]);

gulp.task("release", ["bump"]);

gulp.task("default", ["test"]);
