var API_FILL_REGEX = /[{]([^}]*)[}]/g;

function API_FILL_URL(url, data) {
    return url.replace(API_FILL_REGEX, function (match, p1, offset, string) {
        return (data && data.params && data.params[p1]) || '';
    }) + (data.query ? ('?' + $.param(data.query)) : '');
}

var API = {
    debug: false,
    init: function() {}
};

{{#each methods}}
{{#if operationId}}
{{{ensure-exists 'API' operationId}}}
API.{{dotterize operationId 1}} = function (data, done) {
    if (typeof data === 'function') {
        done = data;
        data = {};
    }

    data = data || {};

    if (!done && this.debug) {
        console.warn('No callback supplied.');
    }

    $.ajax({
        method: '{{upcase method}}',
        url: API_FILL_URL('{{../sdk.url}}{{path}}', data),
        data: '{{upcase method}}' === 'GET' ? undefined : data.payload,
        dataType: 'json',
        jsonp: false,
        headers: data.headers,
        success: function complete(response) {
            typeof done === 'function' && done(null, response);
        },
        error: function error(response) {
            typeof done === 'function' && done(response, null);
        }
    });
};
{{/if}}
{{/each}}

if (typeof window !== 'undefined') window.{{sdk.name}} = API;
module.exports = API;
