'use strict';

var q = require('q');
var validUrl = require('valid-url');

module.exports = {
    getImageBase64: function(url) {
        var deferred = q.defer();

        if (!validUrl.isUri(url)) {
            url = 'http://localhost:' + config.get('port') + url;
        }

        var request = require('request').defaults({ encoding: null });
        logger.info('looking for: ' + url);

        request.get(url, function (error, response, body) {
            if (error) {
                deferred.reject(error);
            } else if (response.statusCode === 200) {
                var data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body, 'base64');
                deferred.resolve(data);
            } else {
                deferred.reject("Response: " + response.statusCode);
            }
        });

        return deferred.promise;
    }
};
