// 3_gallery.js
// This file retrieves all images available with their sampletext, if available

// Includes
var request = require('request');
var http = require('http');
var fs = require('fs');
http.globalAgent.maxSockets = 1000;

// Configuration
var api_url = 'https://v4.alphapicture.com';
var api_username = 'your_username_here';
var api_password = 'your_password_here';

var concurrency = 10;

// Code

var motifList = [];
var motifInfo = JSON.parse(fs.readFileSync('motifs.json'));

// Loads motiflist from first example "1_motifs.js"
for (var i = 0; i < motifInfo.length; i++) {
    for (var j = 0; j < motifInfo[i]['alternatives'].length; j++) {
        motifList.push({
            motifId : motifInfo[i]['id'],
            altId : motifInfo[i]['alternatives'][j]['alternative_id'],
            sampleText : motifInfo[i]['alternatives'][j]['sample_text']
        });
    }
}

function Thread(id) {
    this.id = id;
    this.next();
}

Thread.prototype = {
    next : function() {
        if (motifList.length > 0) {
            var motifToFetch = motifList.shift();
            var requestBody = createRequestBody(motifToFetch['motifId'], motifToFetch['altId'], motifToFetch['sampleText']);
            request({
                uri : api_url + '/Image',
                method : "POST",
                encoding: null,
                headers : {
                    'APIV4-Account' : api_username,
                    'APIV4-Password' : api_password,
                },
                json : requestBody,
                timeout : 60000
            }, (function(motifToFetch, error, response, body) {
                if (!error && response.statusCode == 200 && typeof body == 'object' && body.Error != true) {
                    var filename = '3_' + motifToFetch['motifId'] + '-' + motifToFetch['altId'] + '_' + (+new Date()) + '.jpg';
                    fs.writeFile('./output/' + filename, body, {
                        encoding : 'binary'
                    }, function(err) {
                        if (err) {
                            console.log('Save error', motifToFetch['motifId'], motifToFetch['altId'], err);
                        } else {
                            console.log("Result image saved to output/" + filename);
                        }
                    });
                } else {
                    console.log('Error retrieving motif ', motifToFetch['motifId'], motifToFetch['altId'], error);
                }
                this.next();
            }).bind(this, motifToFetch));
        }
    }
}

for (var i = 0; i < concurrency; i++) {
    new Thread(i);
}

function createRequestBody(motifId, altId, sampleLines) {
    if (JSON.stringify(sampleLines) === '{}') {
        sampleLines = {
            "1" : "Test",
            "2" : "Sample"
        }
    }
    
    return {
        "MotifId" : motifId,
        "AlternativeId" : altId,
        "Lines" : sampleLines,
        "Dimensions" : {
            "w" : 1000,
            "h" : 650
        }
    };
}
