(function () {

    var Ext = window.Ext4 || window.Ext;

    /**
     * @private
     */
    Ext.define('Rally.clientmetrics.monitors.Ajax', {
        singleton: true,
        requires: [
            'Ext.data.Connection'
        ],
        inFlight: 0,

        start: function () {
            Ext.Function.interceptBefore(Ext.Ajax, "request", function () {
                var requestConfig = arguments[0];
                requestConfig.monitor = {
                    started: new Date().getTime()
                };
                Rally.clientmetrics.monitors.Ajax.inFlight++;
                Rally.environment.getMessageBus().publish(Rally.Message.ajaxRequests, {
                    type: 'XHR start, pending: ',
                    toString: function () {
                        return [this.type,
                            Rally.clientmetrics.monitors.Ajax.inFlight,
                            requestConfig.method,
                            requestConfig.url,
                            requestConfig.params.query].join(' ');
                    }
                }, window);

                var callback = requestConfig.callback;
                requestConfig.callback = function () {
                    var requestConfig = arguments[0];
                    Rally.clientmetrics.monitors.Ajax.inFlight++;
                    Rally.environment.getMessageBus().publish(Rally.Message.ajaxRequests, {
                        type: 'XHR end, pending: ',
                        toString: function () {
                            return [this.type,
                                Rally.clientmetrics.monitors.Ajax.inFlight,
                                'elapsed time (ms):',
                                new Date().getTime() - requestConfig.monitor.started].join(' ');
                        }
                    }, window);

                    delete requestConfig.monitor;

                    if (callback) {
                        callback.apply(this, arguments);
                    }
                };
            });
        }
    });
})();