// 5_job.js
// This job shows requesting multiple images in one job ajnd using hotlinks to retrieve them

// 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';

// Code

var requestBody = {
    "Images" : [{
        "MotifId" : "4",
        "AlternativeId" : "1",
        "Template" : {
            1 : "%firstname%"
        },
        "Filename" : "5_1_%number%",
        "Dimensions" : {
            "w" : "1000",
            "h" : "750"
        },
        "Watermark" : false,
        "BadWordFilter" : false
    }, {
        "MotifId" : "2",
        "AlternativeId" : "1",
        "Template" : {
            "1" : "%firstname%"
        },
        "Filename" : "5_2_%number%",
        "Dimensions" : {
            "w" : "1000",
            "h" : "750"
        },
        "Watermark" : false,
        "BadWordFilter" : false
    }, {
        "MotifId" : "81",
        "AlternativeId" : "1",
        "Template" : {
            "1" : "%firstname%"
        },
        "Filename" : "5_3_%number%",
        "Dimensions" : {
            "w" : "1000",
            "h" : "750"
        },
        "Watermark" : false,
        "BadWordFilter" : false
    }],
    "OutputOptions" : {
        "OutputMethod" : "HOTLINK"
    },
    "Data" : [{
        "firstname" : "AlphaPicture",
        "number" : "1"
    }]
};

function Thread() {
	this.doRequest();
}

Thread.prototype = {
	doRequest : function() {
		request({
			uri : api_url + '/Job',
			method : "POST",
			headers : {
				'APIV4-Account' : api_username,
				'APIV4-Password' : api_password,
			},
			json : requestBody,
			timeout : 60000
		}, (function(error, response, body) {
			//console.log(this.id, 'CALLBACK')
			if (!error && response.statusCode == 200 && typeof body == 'object' && body.Error == false) {
				this.startTime = +new Date();
				this.lastRequest = body.JobId;
				console.log('Got JobId', this.lastRequest);
				console.log(body);
				this.checkIfDone();
			} else {
				console.log('Error requesting job', error, JSON.stringify(body));
			}
		}).bind(this));
	},
	checkIfDone : function() {
		var checkRequestBody = {
			Id : this.lastRequest
		};
		request({
			uri : api_url + '/JobInfo',
			method : "POST",
			headers : {
				'APIV4-Account' : api_username,
				'APIV4-Password' : api_password,
			},
			json : checkRequestBody
		}, (function(error, response, body) {
			if (error) {
				console.log('Error in checkIfDone: ' + error);
			} else {
				console.log('body', body);
				if (body.Status != 'DONE' && body.Status != 'ERROR') {
					setTimeout((this.checkIfDone).bind(this), 2000);
				} else {
					if (body.Status == 'DONE') {
						this.endTime = +new Date();
						this.totalTime = this.endTime - this.startTime;
						console.log(this.lastRequest, 'took', this.totalTime, 'ms', 'CDN URLs now available');
						for (var x in requestBody['Images']) {
							for (var y in requestBody['Data']) {
								var filename = requestBody['Images'][x]['Filename'];
								for (var z in requestBody['Data'][y]) {
									filename = filename.replace('%' + z + '%', requestBody['Data'][y][z]);
								}
								console.log(body.CDN + '/' + filename + '.jpg');
							}
						}
					} else {
						console.log('Error occured', body);
					}
				}
			}
		}).bind(this));
	}
}

new Thread();
