"use strict";

var Client = null;
var client = null;

/*
    ajax({
        //additional param to node-rest-client
        url: "url",
        method: "post/get/put",

        // node-rest-client params
        data: "<xml><arg1>hello</arg1><arg2>world</arg2></xml>",
        headers: { "test-header": "client-api" },
        path: { "id": 120 },
        parameters: { arg1: "hello", arg2: "world" },
        proxy: {
            host: "proxy.foo.com", // proxy host
            port: 8080, // proxy port
            user: "ellen", // proxy username if required
            password: "ripley" // proxy pass if required
        },
         // aditional connection options passed to node http.request y https.request methods
         // (ie: options to connect to IIS with SSL)
        connection: {
            secureOptions: constants.SSL_OP_NO_TLSv1_2,
            ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM',
            honorCipherOrder: true
        },
        // customize mime types for json or xml connections
        mimetypes: {
            json: ["application/json", "application/json;charset=utf-8"],
            xml: ["application/xml", "application/xml;charset=utf-8"]
        },
        user: "admin", // basic http auth username if required
        password: "123", // basic http auth password if required
        requestConfig: {
            timeout: 1000, //request timeout in milliseconds
            noDelay: true, //Enable/disable the Nagle algorithm
            keepAlive: true, //Enable/disable keep-alive functionalityidle socket.
            keepAliveDelay: 1000 //and optionally set the initial delay before the first keepalive probe is sent
        },
        responseConfig: {
            timeout: 1000 //response timeout
        }
    }, function(err, data) {
        //handle the result
    });
*/

function setupClientRest(settings) {
    if (!Client) {
        Client = require('node-rest-client').Client;
    }

    client = new Client(settings || {});
}

function ajaxPost(args, callbackAjax) {
    return client.post(args.url, args, callbackAjax);
}

function ajaxGet(args, callbackAjax) {
    return client.get(args.url, args, callbackAjax);
}

function ajaxPut(args, callbackAjax) {
    return client.put(args.url, args, callbackAjax);
}

function ajaxDelete(args, callbackAjax) {
    return client.delete(args.url, args, callbackAjax);
}

function ajaxPatch(args, callbackAjax) {
    return client.patch(args.url, args, callbackAjax);
}

function handleError(err, callback) {
    logger.warn(JSON.stringify(err));
    if (typeof callback === 'function') {
        callback(new Error(err));
    }
}

function handleSuccess(data, response, callback) {
    if (typeof callback === 'function') {
        callback(null, data);
    }
}

function processAjaxRequest(settings, callbackAjax) {
    var method = settings.method;
    method = method ? method.toUpperCase() : "GET"; //default is GET method

    var req = null;
    switch (method) {
        case "PUT":
            req = ajaxPut(settings, callbackAjax);
            break;
        case "POST":
            req = ajaxPost(settings, callbackAjax);
            break;
        case "DELETE":
            req = ajaxDelete(settings, callbackAjax);
            break;
        case "PATCH":
            req = ajaxPatch(settings, callbackAjax);
            break;
        default:
            req = ajaxGet(settings, callbackAjax);
    }

    req.on("error", function (err) {
        callbackAjax(null, null, err);
    });
}

function ajax(settings, callback) {
    if (settings) {
        var callbackAjax = function (data, response, error) {
            if (error) {
                callback(error);
            } else if (response.statusCode >= 200 && response.statusCode <= 299) {
                handleSuccess(data, response, callback);
            } else {
                var msg = "Something is error on the target: " + response.statusCode;
                logger.warn(msg);
                handleError(msg, callback);
            }
        };

        setupClientRest(settings);

        processAjaxRequest(settings, callbackAjax);
    } else {
        var err = new Error("No settings passed to ajax function");
        callback(err);
    }
};

module.exports.ajax = ajax;