﻿/* Service Proxy */
function serviceProxy(serviceUrl) {
    var me = this;
    this.serviceUrl = serviceUrl;

    this.invoke = function(method, data, callback, error, bare) {
        // convert object to JSON
        var json = JSON.stringify(data);
        // build method URL based on base service path
        var url = me.serviceUrl + method;

        $.ajax({
            url: url,
            data: json,
            type: 'POST',
            processData: false,
            contentType: 'application/json',
            timeout: 10000,
            dataType: 'json',
            success: function(result) {
                // if no callback defined, do nothing
                if (!callback) return;
                // if object returned is the result, use it
                if (bare) {
                    callback(result);
                    return;
                }
                // wrapped message contains top object node - strip it off
                for (var property in result) {
                    callback(result[property]);
                    break;
                }
            },
            error: function(xhr) {
                // if no error callback defined, do nothing
                if (!error) return;
                // if error message set
                if (xhr.responseText) {
                    // parse message
                    var err = JSON.parse(xhr.responseText);
                    // send error message on
                    if (err) {
                        error(err);
                    } else {
                        error({ Message: 'Unknown server errror' });
                    }
                }
            }
        });
    }
}