import { taskMaker } from '../taskMaker';

import gutil from 'gulp-util';

import { Server } from 'karma';
import { parseConfig } from 'karma/lib/config';


function testTasks(gulp, config) {
    const karmaConfigFilePath = process.cwd() + '/' + config.paths.config.karma;

    taskMaker(gulp)
        .createTask({
            name: 'test',
            desc: 'Run Karma tests',
            fn: runTests,
        })
        .createTask({
            name: 'test:fail',
            fn: runTestsAndFailOnFail,
        })
        .createTask({
            name: 'tdd',
            desc: 'Run continous Karma tests',
            fn: runTdd,
        });

    function runKarma(configFilePath, options, cb, exitFn) {
        const parsedKarmaConfig = parseConfig(configFilePath, {});
        const exit = !exitFn ?  generateExitFn(cb) : exitFn;

        Object.keys(options).forEach(key => {
            parsedKarmaConfig[key] = options[key];
        });

        Server.start(parsedKarmaConfig, exit);
    }


    function runTests(done) {
        runKarma(karmaConfigFilePath, {
            singleRun: true,
        }, done);
    }

    function runTdd(done) {
        runKarma(karmaConfigFilePath, {}, done);
    }

    function runTestsAndFailOnFail(done) {
        runKarma(karmaConfigFilePath, { singleRun: true }, done, exitCode => {
            if (exitCode === 1) {
                gutil.log(gutil.colors.red('=========================='));
                gutil.log(gutil.colors.red('Unit tests failed, exiting.'));
                gutil.log(gutil.colors.red('=========================='));

                done('Unit tests failed');
            } else {
                done();
            }
        });
    }

    function generateExitFn(cb) {
        return exitCode => {
            cb();
            process.exit(exitCode);
        };
    }
}

export { testTasks };

@@ -526,32 +526,127 @@
   .createTask(%7B%0A
+            name: 'test:ci',%0A            fn: runTestsAndExit,%0A        %7D)%0A        .createTask(%7B%0A
             name
@@ -1435,16 +1435,342 @@
         
+parseTestResults(exitCode, done);%0A        %7D);%0A    %7D%0A%0A    function runTestsAndExit(done) %7B%0A        runKarma(karmaConfigFilePath, %7B singleRun: true %7D, done, exitCode =%3E %7B%0A            parseTestResults(exitCode, done);%0A            process.exit(exitCode);%0A        %7D);%0A    %7D%0A%0A    function parseTestResults(exitCode, done) %7B%0A        
 if (exit
@@ -1779,28 +1779,24 @@
 de === 1) %7B%0A
-    
             
@@ -1858,36 +1858,32 @@
 ));%0A            
-   
- 
 gutil.log(gutil.
@@ -1922,28 +1922,24 @@
 xiting.'));%0A
-    
             
@@ -2006,28 +2006,24 @@
             
- 
-   
 done('Unit t
@@ -2045,20 +2045,16 @@
         
-  
-  
 %7D else %7B
@@ -2054,20 +2054,16 @@
  else %7B%0A
-    
         
@@ -2086,25 +2086,9 @@
     
-    %7D%0A        %7D);
+%7D
 %0A   

add gulp:ci task