/**
 * Proxy to send request directly to the econda tracking server.
 * See econda.proxy for information, how to configure the proxy.
 * 
 * @class econda.proxy.Direct
 */
econda.proxy.Direct = function(cfg)
{
    var cmp = this;
    
    /**
     * Private members collection
     * @property {Object} __p Collection of private properties
     * @private
     */
    var __p = {
        /**
         * @cfg {Number/String} [keepalive="auto"]
         * Number of seconds between keepalive requests. Use "auto" to let the tracker
         * calculate the keepalive frequencey automaticall. We'll use longere periods for
         * long videos than for short ones. Use 0 to disable keepalive server calls.
         */
        keepalive: "auto",
        
        /**
         * @cfg {Boolean} [disabled: false]
         * If set to true, we'll not send any request to the tracking server.
         * This option is intended for testing only
         */
        disabled: false
    };
    
    /**
     * Stores the data of last server call.
     * @property {Object} _lastRequest
     * @private
     */
    this._lastRequest = null;
    
    /**
     * Reference to keepalive handlers {"trackerId": reference}
     * @private
     * @property {Object} keepaliveHandler collection of keepalive handlers
     */
    var keepaliveHandler = {};
    
    /**
     * Send media event.
     * @method
     * @protected
     * @property {econda.proxy.MediaEvent} mediaEvent Event object
     * @return {econda.proxy.Direct}
     */
    this.sendMediaEvent = function(mediaEvent) 
    {
        if(!(mediaEvent instanceof econda.proxy.MediaEvent)) {
            econda.debug.error("Proxy.sendMediaEvent expects object of type econda.proxy.MediaEvent as parameter");
        }
        var srvEventName, // event name as expected by tracking server
            eventName = mediaEvent.getEventName();

        switch(mediaEvent.getEventName()) {
        case "keepalive":
            srvEventName = "keepalive";
            break;
        case "play":
            srvEventName = "play";
            break;
        case "pause":
            srvEventName = "pause";
            break;
        case "stop":
            srvEventName = "ended";
            break;
        default:
            // currently not supported by this proxy
            return;
        }
        
        // collect data we'll send to server
        var data = [
            // name of media file as we'l show it in monitor ui
            // toString will return the main category followed by content name
            mediaEvent.getContentLabel(),
            
            // Event name. Currently supported "play", "pause", "ended"
            srvEventName,
            
            // Media type, must be "audio" or "video"
            mediaEvent.getMediaType(),
            
            // current position in seconds
            mediaEvent.getPosition(),
            
            // duration of on demand media file
            mediaEvent.getDuration(),
            
            // time since page load
            Math.round((new Date().getTime() - econda.proxy.__pageInitDate.getTime())),
            
            // counter for each movie
            mediaEvent.getTrackerId(),
            
            // previewUri
            mediaEvent.getPreviewUri()
        ];
        
        econda.debug.log("Sending media event: " + eventName, data);
        var dataToSend = {
                type: 'event',
                media: data
            };
        if(!this.isDisabled()) {
            window.emosPropertiesEvent(dataToSend);
        } else {
            econda.debug.log("Request not send, tracking is disabled in proxy.");
        }
        // store last request (required for unit tests)
        this._lastRequest = dataToSend;
        
        // start / top keepalive
        if(eventName == "play") {
            cmp.startKeepalive(mediaEvent);
        }
        if(eventName == "pause" || eventName == "stop") {
            cmp.stopKeepalive(mediaEvent);
        }
        
        return this;
    };
    
    /**
     * Starts sending keepalive requests to tracking server
     * @method
     * @param {econda.proxy.MediaEvent} mediaEvent
     * @private
     */
    this.startKeepalive = function(mediaEvent)
    {
        var keepaliveInterval,
            trackerId = mediaEvent.getTrackerId(),
            keepaliveEvent;
        
        if(__p["keepalive"] != "0") {
            keepaliveEvent  = mediaEvent.copy();
            keepaliveEvent.setEventName("keepalive");
            keepaliveInterval = isNaN(__p["keepalive"]) ? 10000 : __p["keepalive"];
            
            keepaliveHandler[trackerId] = setInterval(function(){
                keepaliveEvent.setPosition(keepaliveEvent.getPosition()+(keepaliveInterval/1000));
                cmp.sendMediaEvent(keepaliveEvent);
            }, keepaliveInterval);
        }
        return this;
    };
    
    /**
     * Stop sending keepaliv requests
     * @method
     * @private
     */
    this.stopKeepalive = function(mediaEvent)
    {
        var trackerId = mediaEvent.getTrackerId();
        if(typeof keepaliveHandler[trackerId] != 'undefined') {
            clearInterval(keepaliveHandler[trackerId]);
        }
        return this;
    };
    
    /**
     * Set new keepalive value in seconds or "auto" for auto calcualtion
     * @method
     * @param {Number/String} seconds Number of seconds or "auto"
     */
    this.setKeepalive = function(seconds)
    {
        if(typeof seconds != 'number' && seconds != 'auto') {
            econda.debug.error("Got invalid value for MediaTracker.keepalive: " + seconds);
        } else {
            __p["keepalive"] = seconds;
        }
        return this;
    };
    
    /**
     * Get current keepalive setting
     * @method
     * @return {Number/String}
     */
    this.getKeepalive = function()
    {
        return __p["keepalive"];
    };
    
    /**
     * Disable tracking
     * @method
     */
    this.disable = function()
    {
        __p["disabled"] = true;
        return this;
    };
    
    /**
     * Enable tracking
     * @method
     */
    this.enable = function()
    {
        __p["disabled"] = false;
        return this;
    };

    /**
     * Set new status for disabled property
     * @param {Boolean} isDisabled True to disable, false to enabled
     */
    this.setDisabled = function(isDisabled)
    {
        __p["disabled"] = (isDisabled == true);
        return this;
    };
    
    /**
     * True if tracking is disabled
     * @method
     */
    this.isDisabled = function()
    {
        return __p["disabled"];
    };
    
    /**
     * Dummy function, you can't change the type of a proxy this way.
     * Use econda.proxy.configure() instead.
     * @method {String} type Proxy type, must be "direct"
     * @ignore
     */
    this.setType = function(type)
    {
        var type = type || "";
        
        if(type.toLowerCase() != 'direct') {
            econda.debug.error("You can't change the type of proxies use setType. Use econda.proxy.configure instead.");
        }
        return this;
    };
    
    return this.setup(cfg, __p);
};
econda.proxy.Direct.prototype = new econda.base.Object();