var os = require('os');
var path = require('path');
var fs = require('fs');
var swig = require('swig');


var KarmaDataurlReporter = function(baseReporterDecorator, config, logger, helper, formatError, emitter) {

  var log = logger.create('reporter.dataurl');
  var reporterConfig = config.dataurlReporter || {};
  var canvases = {};
  var results = [];

  var pkgName = reporterConfig.suite || '';

  var outputFile = helper.normalizeWinPath(path.resolve(config.basePath, reporterConfig.outputFile
      || 'dataurl-results.html'));

  var templateFile = helper.normalizeWinPath(path.resolve(config.basePath, reporterConfig.templateFile
      || __dirname+"/defaulttemplatereport.html"));

  var reportTitle = reporterConfig.reportTitle || 'CANVASES';

  var html = "";
  var pendingFileWritings = 0;
  var fileWritingFinished = function() {};
  var allMessages = [];


  baseReporterDecorator(this);


  this.adapters = [function(msg) {
    allMessages.push(msg);
  }];

  // étend la classe Browser pour attraper les dataurl avant qu’elles n’arrivent dans 
  // la sortie console !!!
  this.onBrowserStart = function(browser) {
        var baseInfo = browser.onInfo;
        browser.onInfo = function(info) {
        if(info.log.dataurl) {
          var dto = info.log;
          if(!canvases[dto.id]) {
            canvases[dto.id] = {result:{}, canvases: []};
          }
          canvases[dto.id].canvases.push(dto);
          info = {log:'DataurlReporter:: reporting dataurl for ' + dto.id + ' (' + browser.name + ')', type:'info'};
        } 
        baseInfo.call(browser, info);
      };
  };

  this.specSuccess = this.specSkipped = this.specFailure = function(browser, result) {
    results.push(result);
  };

  this.onRunComplete = function() {
    pendingFileWritings++;


    results.forEach(function(result) {
      if(!!canvases[result.id]) {
          canvases[result.id].result = result;
      }
    });

    var html = swig.renderFile(templateFile, {
      title: reportTitle,
      tests: canvases
    });

    canvases ={};
    results = [];

    helper.mkdirIfNotExists(path.dirname(outputFile), function() {
      fs.writeFile(outputFile, html, function(err) {
        if (err) {
          log.warn('Cannot write HTML\n\t' + err.message);
        } else {
          log.debug('Dataurls written to "%s".', outputFile);
        }

        if (!--pendingFileWritings) {
          fileWritingFinished();
        }
      });
    });
  };

  // wait for writing all the xml files, before exiting
  this.onExit = function(done) {
    if (pendingFileWritings) {
      fileWritingFinished = done;
    } else {
      done();
    }
  };
};

KarmaDataurlReporter.$inject = ['baseReporterDecorator', 'config', 'logger', 'helper', 'formatError', 'emitter'];

module.exports = {
  'reporter:dataurl': ['type', KarmaDataurlReporter]
};

@@ -99,16 +99,341 @@
 ig');%0A%0A%0A
+var slug = function (input) %7B%0A    return input.toString().toLowerCase()%0A        .replace(/%5Cs+/g, '')           // Replace spaces with -%0A        .replace(/%5B%5E%5Cw%5C-%5D+/g, '')       // Remove all non-word chars%0A        .replace(/%5C-/g, '')         // Replace multiple - with single -%0A        ;%0A%7D;%0A%0Aswig.setFilter('slugify', slug);%0A%0A
 var Karm
@@ -649,18 +649,18 @@
 vases = 
-%7B%7D
+%5B%5D
 ;%0A  var 
@@ -1592,16 +1592,17 @@
 fo.log;%0A
+%0A
         
@@ -1607,28 +1607,94 @@
     
-if(!canvases%5Bdto.id%5D
+var match = false;%0A          var idx;%0A          for (idx=0; idx%3Ccanvases.length; idx++
 ) %7B%0A
@@ -1697,32 +1697,35 @@
 ) %7B%0A            
+if(
 canvases%5Bdto.id%5D
@@ -1721,56 +1721,281 @@
 ses%5B
-dto.id%5D = %7Bresult:%7B%7D, canvases: %5B%5D%7D;%0A          %7D
+idx%5D.id == dto.id) %7B%0A              match=true;%0A              break;%0A            %7D%0A          %7D %0A          if(match===false) %7B%0A            canvases.push(%7Bid: dto.id, result:%7B%7D, canvases: %5B%5D%7D);%0A            idx = canvases.length-1;%0A          %7D%0A%0A          dto.browser = browser;
 %0A   
@@ -2010,22 +2010,19 @@
 anvases%5B
-dto.
 id
+x
 %5D.canvas
@@ -2449,32 +2449,206 @@
     
-if(!!canvases%5Bresult.id%5D
+var match = false;%0A      var idx;%0A      for (idx=0; idx%3Ccanvases.length; idx++) %7B%0A        if(canvases%5Bidx%5D.id == result.id) %7B%0A          match=true;%0A          break;%0A        %7D%0A      %7D %0A      if(match
 ) %7B%0A
@@ -2670,25 +2670,63 @@
 ses%5B
+idx%5D.
 result
-.
+ = result;%0A          canvases%5B
 id
+x
 %5D.r
-esult
+ootSuite
  = r
@@ -2722,32 +2722,41 @@
 otSuite = result
+.suite%5B0%5D
 ;%0A      %7D%0A    %7D)
@@ -2876,18 +2876,18 @@
 nvases =
-%7B%7D
+%5B%5D
 ;%0A    re
@@ -2899,16 +2899,17 @@
  = %5B%5D;%0A%0A
+%0A
     help

send more infos to the template