// require mde-node metrics as a workaround for
// https://github.com/sindresorhus/gulp-mocha/issues/86
/* eslint no-unused-vars: 0 */
import metrics from "mde-node-metrics";

import config from "../config";
import gulp from "gulp";
import gutil from "gulp-util";
import istanbul from "gulp-istanbul";
import mocha from "gulp-mocha";

/* isparta 3.1.0 has a bug that forces us to use require instead of import
 * https://github.com/douglasduteil/isparta/issues/45 */
isparta = require("isparta");

const conf = config.get(),

function showError(error) {
    const msg =
            error.message === "Coverage failed" ?
            "Code coverage needs to be at least " + conf.coverage + "%" : null;
    gutil.log(gutil.colors.red(msg || error));
    process.exit(1); // eslint-disable-line no-process-exit
}

function runTests(cb) {
    gulp.src([
        "test/util/beforeTest.js",
        "test/app/**/*-test.js"
    ], {
        read: false
    })
        .pipe(mocha(conf.mocha))
        .on("error", showError)
        .pipe(istanbul.writeReports(conf.istanbul))
        .pipe(istanbul.enforceThresholds({
            thresholds: {
                global: conf.coverage
            }
        }))
        .on("end", cb);
}

export default cb => {
    gulp.src([
        "app/**/*.js"
    ])
        .pipe(istanbul({
            instrumenter: isparta.Instrumenter,
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire())
        .on("finish", () => runTests(cb));
};