(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     * @private
     * Simple monitor class that logs (to Ext.log and ClientMetrics) when there is high latency.
     */
    Ext.define('Rally.clientmetrics.monitors.Default', {
        extend: 'Rally.clientmetrics.monitors.Monitor',
        requires: [
            'Rally.MessageBus',
            'Rally.Message'
        ],
        mixins: {
            clientMetrics: 'Rally.clientmetrics.ClientMetricsRecordable'
        },

        //threshold of latency over which the latencyThresholdExceeded method will be invoked
        //Chrome seems to self-idle if the user is not interacting with the page - it is common to see
        //idle time around 900 ms but only when the window is not in focus and on a laptop
        latencyThreshold: 200,
        publishThreshold: 350,

        latencyExceededMessage: 'Latency threshold exceeded. Custom message.',

        latencyThresholdExceeded: function (latency, timeInterval) {
            if (!document.hasFocus()) {
                return;
            }
            var now = new Date().getTime();

            Ext.log(timeInterval + ' latency exceeded! - ' + latency);

            Rally.environment.getMessageBus().publish(Rally.Message.clientLatency, {
                latency: latency,
                time: now,
                type: 'clientLatency',
                toString: function () {
                    return [this.type, ' latency: ', this.latency, ' ts: ', this.time].join('');
                }
            }, window);

            if (latency >= this.publishThreshold) {
                this.recordLoadBegin({
                    description: 'Client latency (estimated)',
                    startTime: now - latency,
                    miscData: {
                        latencyDetected: latency,
                        latencyInterval: timeInterval
                    }
                });

                this.recordLoadEnd({
                    stopTime: now
                });
            }
        }
    });
})();