// 4_job.js
// Retrieves a job

// 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+2+3' : "Hello %firstname%"
        },
        "Filename" : "4_%number%",
        "Dimensions" : {
            "w" : "1000",
            "h" : "750"
        },
        "Watermark" : false,
        "BadWordFilter" : false
    }],
    "OutputOptions" : {
        "OutputMethod" : "ZIP"
    },
    "Data" : [{
        "firstname" : "AlphaPicture",
        "number" : "1"
    }, {
        "firstname" : "Homer",
        "number" : "2"
    }, {
        "firstname" : "Lisa",
        "number" : "3"
    }, {
        "firstname" : "Bart",
        "number" : "4"
    }, {
        "firstname" : "Midge has a very long name which will be split",
        "number" : "5"
    }]
};

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 != true) {
                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', 'retrieving now by key', body.Key);
                        request(api_url + '/Result/' + body.Key).pipe(fs.createWriteStream('./output/4_' + body.JobId + '.zip'));
                    } else {
                        console.log('Error occured', body);
                    }
                }
            }
        }).bind(this));
    }
}

new Thread();
