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

var constants = require('../../tasks/util/constants');
var getOptions = require('../../tasks/util/get_image_request_options');

// packages inside the image server docker
var request = require('request');
var test = require('tape');
var gm = require('gm');


// make artifact folders
if(!fs.existsSync(constants.pathToTestImagesDiff)) fs.mkdirSync(constants.pathToTestImagesDiff);
if(!fs.existsSync(constants.pathToTestImages)) fs.mkdirSync(constants.pathToTestImages);

var userFileName = process.argv[2];

var touch = function(fileName) {
    fs.closeSync(fs.openSync(fileName, 'w'));
};

if (!userFileName) runAll();
else runSingle(userFileName);

function runAll () {
    test('testing mocks', function (t) {

        console.error('### beginning pixel comparison tests ###');
        var files = fs.readdirSync(constants.pathToTestImageMocks);

        // -1 for font-wishlist and
        // -38 for the gl2d mocks
        // -1 for gl3d_bunny-hull
        t.plan(files.length - 40);

        for (var i = 0; i < files.length; i ++) {
            testMock(files[i], t);
        }

    });
}

function runSingle (userFileName) {
    test('testing single mock: ' + userFileName, function (t) {
        t.plan(1);
        testMock(userFileName, t);
    });
}

function testMock (fileName, t) {
    if(path.extname(fileName) !== '.json') return;
    if(fileName === 'font-wishlist.json' && !userFileName) return;

    // TODO fix race condition in gl2d image generation
    if(fileName.indexOf('gl2d_') !== -1) return;

    // TODO fix run-to-run randomness
    if(fileName === 'gl3d_bunny-hull.json') return;

    var figure = require(path.join(constants.pathToTestImageMocks, fileName));
    var bodyMock = {
        figure: figure,
        format: 'png',
        scale: 1
    };

    var imageFileName = fileName.split('.')[0] + '.png';
    var savedImagePath = path.join(constants.pathToTestImages, imageFileName);
    var diffPath = path.join(constants.pathToTestImagesDiff, 'diff-' + imageFileName);
    var savedImageStream = fs.createWriteStream(savedImagePath);
    var options = getOptions(bodyMock, 'http://localhost:9010/');
    var statusCode;

    function checkImage () {
        var options = {
            file: diffPath,
            highlightColor: 'purple',
            tolerance: 0.0
        };

        if(statusCode === 485) {
            console.error(imageFileName, '- skip');
        }
        else {
            gm.compare(
                savedImagePath,
                path.join(constants.pathToTestImageBaselines, imageFileName),
                options,
                onEqualityCheck
            );
        }
    }

    function onEqualityCheck (err, isEqual) {
        if (err) {
            touch(diffPath);
            return console.error(err, imageFileName);
        }
        if (isEqual) {
            fs.unlinkSync(diffPath);
            console.error(imageFileName + ' is pixel perfect');
        }

        t.ok(isEqual, savedImagePath + ' should be pixel perfect');
    }

    request(options)
        .on('response', function(response) {
            statusCode = response.statusCode;
        })
        .pipe(savedImageStream)
        .on('close', checkImage);
}

@@ -764,75 +764,8 @@
  %7B%0A%0A
-        console.error('### beginning pixel comparison tests ###');%0A
     
@@ -2120,28 +2120,8 @@
 /');
-%0A    var statusCode;
 %0A%0A  
@@ -2280,122 +2280,8 @@
 %7D;%0A%0A
-        if(statusCode === 485) %7B%0A            console.error(imageFileName, '- skip');%0A        %7D%0A        else %7B%0A    
     
@@ -2296,20 +2296,16 @@
 ompare(%0A
-    
         
@@ -2320,28 +2320,24 @@
 dImagePath,%0A
-    
             
@@ -2410,20 +2410,16 @@
         
- 
-   
 options,
@@ -2419,20 +2419,16 @@
 ptions,%0A
-    
         
@@ -2459,24 +2459,10 @@
     
-    );%0A        %7D
+);
 %0A   
@@ -2687,72 +2687,8 @@
 h);%0A
-            console.error(imageFileName + ' is pixel perfect');%0A
     
@@ -2716,30 +2716,29 @@
 sEqual, 
-savedImagePath
+imageFileName
  + ' sho
@@ -2793,110 +2793,8 @@
 ns)%0A
-        .on('response', function(response) %7B%0A            statusCode = response.statusCode;%0A        %7D)%0A
     

clean up compare pixel test logs