var realtime = {};

realtime.current = {};
realtime.timeouts = [];

realtime.get_data = function (params, callback) {
    var url = mp.globals.domain + "/api/2.0/events/top/";
    
    if (mp.report.globals.api_sig) { params.api_sig = mp.report.globals.api_sig; }
    
    $.getJSON(url,params, function(data) {
            callback(data);
    });
    
    // Restart realtime polling if something happens
    // Not perfect, but should work 95% of the time.
    realtime.timeouts.push(setTimeout(function() {
        realtime.get_data(params, callback);
    }, 35000));
};

realtime.update = function(data) {
    /*  Reset timeout list every time data is returned
        This will prevent runaway processes - if multiple 
        timeouts start going at once, they will eventually 
        be canceled.
    */
    var build_pct = function(pct) {
        html = '';
        if (pct !== null) {
            if (pct < 0) {
                html += '<span class="red">';
            } else if (pct > 0) {
                html += '<span class="green">+';
            } else {
                html += '<span class="black">';
            }
            html += mp.utility.commaize(mp.utility.floatformat(pct * 100, 1)) + '%</span>';
        }
        return html;
    };
    
    for (var t in realtime.timeouts) {
        clearTimeout(realtime.timeouts[t]);
    }
    realtime.timeouts = [];

    // Only update table if the endpoint is still correct
    if (data.type == mp.report.globals.table_params.type) {
        var analysis_type = data.type;
        data = data.events;
        for (var d in data){
            if (d) {
                if (!(data[d].event in realtime.current)) {
                    realtime.current[data[d].event] = {'amount': data[d].amount, 'percent_change': data[d].percent_change};
                }
                setTimeout((function (d, analysis_type) { 
                    return function () {                        
                        if (analysis_type == mp.report.globals.table_params.type) {
                            var row_id = mp.report.globals.wrappers.event.index[data[d].event];
                            var amt = $("#" + row_id + " .today .amount");
                            var pct = $("#" + row_id + " .today .percent");
                            var current = parseFloat(amt.text().replace(',', ''), 10);
                            // Keep updating percent when total is unchanged.
                            if (realtime.current[data[d].event] && realtime.current[data[d].event].amount == data[d].amount ) {
                                // Add + if positive delta
                                pct.html(build_pct(data[d].percent_change));
                            }

                            var shortened_amount = mp.utility.floatformat(data[d].amount, 1);
                            // Update total, percent if it changed
                            if (shortened_amount > current) {
                                amt.fadeOut(200, function() {
                                    amt.html(mp.utility.commaize(shortened_amount));
                                    pct.html(build_pct(data[d].percent_change));
                                    amt.fadeIn(100); 
                                });
                                
                                realtime.current[data[d].event] = {'amount': data[d].amount, 'percent_change': data[d].percent_change};
                            }
                            // Uncomment for auto sorting. Need to change to a stable sort for this to work well.
                            //mp.report.events.views.table.sort();
                        }
                    }; 
                })(d, analysis_type), Math.floor(Math.random()*7000));
            }
        }
    }
    
    realtime.timeouts.push(setTimeout(function() {
        realtime.get_data({
            'api_sig': mp.report.globals.api_sig,
            'interval': 1,
            'limit': 255,
            'project_id': mp.report.globals.project_id,
            'unit': 'day',
            'type': mp.report.globals.table_params.type
            }, realtime.update);
    }, 7000));

};
