// 2_image.js
// This file retrieves a single image from the API

// 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 = {
    "MotifId" : "974",
    "AlternativeId" : "1",
    "Lines" : {
        "1" : "Test"
    },
    "Dimensions" : {
        "w" : "800",
        "h" : "500"
    },
    "Watermark": true
};

request({
    uri : api_url + '/Image',
    method : "POST",
    encoding: null,
    headers : {
        'APIV4-Account' : api_username,
        'APIV4-Password' : api_password,
    },
    json : requestBody
}, function(error, response, body) {
    if (!error && response.statusCode == 200) {
        var filename = '2_' + (+new Date()) + '.jpg';
        fs.writeFile('./output/' + filename, body, {
            encoding : 'binary'
        }, function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("Result image saved to output/" + filename);
            }
        });
    } else {
        console.log('Error: ', error, body);
    }
});
