﻿// muxer.js
// Combines calls to echo APIs

(function($) {
    if (!window.Echo) window.Echo = {};
    if (!window.Echo.Muxer) {
        window.Echo.Muxer = {};

        var echoKey = null;
        var muxApiEndpoint = "http://api.echoenabled.com/v1/mux";
        var maxQueueLength = 2000; // in characters. Not including callback and appkey parameters.

        var queue = [];
        var queueLength = 2; // in characters of JSON text. Start at 2 to account for the enclosing brackets
        var callbacks = [];

        /**
         * Muxer.setApiKey()
         * Sets the Echo API key. This must be set before calling add() or execute()
         */
        window.Echo.Muxer.setApiKey = function(key) {
            echoKey = key;
        };

        /**
         * Muxer.add()
         * Adds an API call to the queue
         *
         * @param o         - object with two properties:
         *                      method - string - either "count" or "search"
         *                      q      - string - An Echo query
         * @param callback  - function(data) - will be called with the results of the API call
         */
        window.Echo.Muxer.add = function(o, callback) {
            o.id = queue.length;
            var request = JSON.stringify(o);

            if (queueLength + request.length > maxQueueLength) {
                Echo.Muxer.execute();
                o.id = queue.length;
                request = JSON.stringify(o);
            }

            queue.push(request);
            queueLength += request.length + 1; // add 1 for the comma between objects
            callbacks.push(callback);
        };

        /**
         * Muxer.execute()
         * Executes the queued requests. NOTE: The requests are not guaranteed to wait for this call!
         * If the queue fills up, it will be executed early.
         */
        window.Echo.Muxer.execute = function() {
            if (queue.length > 0) {
                var request = '[' + queue.join(',') + ']';
                var callbacksCaptured = callbacks.slice();
        
                function response(data) {
                    $.each(data, function(id, data) {
                        callbacksCaptured[id](data);
                    });
                }
                $.get(muxApiEndpoint, {appkey: echoKey, requests: request}, response, "jsonp");
                callbacks.length = 0;
                queue.length = 0;
                queueLength = 2;
            }
        };
    }
})(jQuery);
