var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/// <reference path="../../base/BaseClass.ts" />
/// <reference path="../../lib-definitions/emos.d.ts" />
/// <reference path="MediaEvent.ts" />
/// <reference path="Proxy.ts" />
var econda;
(function (econda) {
    var media;
    (function (media) {
        var transport;
        (function (transport) {
            var MediaEvent = econda.media.transport.MediaEvent;
            /**
            * Proxy to send request directly to the econda tracking server.
            * See econda.media.transport.Proxy for information, how to configure the proxy.
            *
            * @class econda.media.transport.Direct
            */
            var Direct = (function (_super) {
                __extends(Direct, _super);
                function Direct(cfg) {
                    _super.call(this);
                    /**
                     * 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.
                     * @cfg {Number/String} [keepalive="auto"]
                     * @accessor
                     */
                    this.keepalive = Direct.INTERVAL_AUTO;
                    this.getKeepalive = function () {
                        return this.keepalive;
                    };
                    /**
                     * @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
                     */
                    this.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
                     */
                    this.keepaliveHandler = {};
                    if (cfg instanceof Direct) {
                        return cfg;
                    }
                    this.initConfig(cfg);
                }
                /**
                 * Ignore type property in config.
                 * @private just for docs
                 */
                Direct.prototype.setType = function (type) {
                    if (type.toLowerCase() != 'direct') {
                        econda.debug.error('econda.media.transport.Direct accepts only type=direct');
                    }
                    return this;
                };
                Direct.prototype.setKeepalive = function (seconds) {
                    if (typeof seconds != 'number' && seconds != 'auto') {
                        econda.debug.error("Got invalid value for MediaTracker.keepalive: " + seconds);
                    }
                    else {
                        this.keepalive = seconds;
                    }
                    return this;
                };
                /**
                 * Disable tracking
                 * @method
                 */
                Direct.prototype.disable = function () {
                    this.disabled = true;
                    return this;
                };
                /**
                 * Enable tracking
                 * @method
                 */
                Direct.prototype.enable = function () {
                    this.disabled = false;
                    return this;
                };
                /**
                 * Set new status for disabled property
                 * @param {Boolean} isDisabled True to disable, false to enabled
                 */
                Direct.prototype.setDisabled = function (isDisabled) {
                    this.disabled = (isDisabled == true);
                    return this;
                };
                /**
                 * True if tracking is disabled
                 * @method
                 */
                Direct.prototype.isDisabled = function () {
                    return this.disabled;
                };
                /**
                 * Send media event.
                 * @method
                 * @property {econda.media.transport.MediaEvent} mediaEvent Event object
                 * @return {econda.media.transport.Direct}
                 */
                Direct.prototype.sendMediaEvent = function (mediaEvent) {
                    if (!(mediaEvent instanceof MediaEvent)) {
                        econda.debug.error("Proxy.sendMediaEvent expects object of type econda.media.transport.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 this;
                    }
                    // 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", "keepalive"
                        srvEventName,
                        // Media type, must be "audio" or "video"
                        mediaEvent.getMediaType(),
                        // current position in seconds
                        mediaEvent.getPosition(),
                        // duration of on media file
                        mediaEvent.getDuration(),
                        // time since page load
                        Math.round((new Date().getTime() - econda.media.transport.Proxy.__pageInitDate.getTime())),
                        // counter for each movie
                        mediaEvent.getTrackerId(),
                        // previewUri
                        mediaEvent.getPreviewUri() ? mediaEvent.getPreviewUri().toString() : null
                    ];
                    econda.debug.log("Sending media event: " + eventName, data);
                    var dataToSend = {
                        type: 'event',
                        media: data
                    };
                    if (!this.isDisabled()) {
                        if (emos3 && emos3.send) {
                            emos3.send(dataToSend);
                        }
                        else if (emosPropertiesEvent) {
                            emosPropertiesEvent(dataToSend);
                        }
                        else {
                            econda.debug.error("Could not sent media event: Neither emosPropertiesEvent nor emos3.send is defined.");
                        }
                    }
                    else {
                        econda.debug.log("Request not sent, tracking is disabled in proxy.");
                    }
                    // store last request (required for unit tests)
                    this._lastRequest = dataToSend;
                    // start / top keepalive
                    if (eventName == "play") {
                        this.startKeepalive(mediaEvent);
                    }
                    if (eventName == "pause" || eventName == "stop") {
                        this.stopKeepalive(mediaEvent);
                    }
                    return this;
                };
                /**
                 * Starts sending keepalive requests to tracking server
                 * @method
                 * @param {econda.media.transport.MediaEvent} mediaEvent
                 * @private
                 */
                Direct.prototype.startKeepalive = function (mediaEvent) {
                    var cmp = this;
                    var keepaliveInterval, trackerId = mediaEvent.getTrackerId(), keepaliveEvent;
                    if (this.keepalive != "0") {
                        keepaliveEvent = mediaEvent.clone();
                        keepaliveEvent.setEventName("keepalive");
                        keepaliveInterval = this.keepalive == Direct.INTERVAL_AUTO ? 10000 : Number(this.keepalive);
                        this.keepaliveHandler[trackerId] = setInterval(function () {
                            keepaliveEvent.setPosition(keepaliveEvent.getPosition() + (keepaliveInterval / 1000));
                            cmp.sendMediaEvent(keepaliveEvent);
                        }, keepaliveInterval);
                    }
                    return this;
                };
                /**
                 * Stop sending keepaliv requests
                 * @method
                 * @private
                 */
                Direct.prototype.stopKeepalive = function (mediaEvent) {
                    var trackerId = mediaEvent.getTrackerId();
                    if (typeof this.keepaliveHandler[trackerId] != 'undefined') {
                        clearInterval(this.keepaliveHandler[trackerId]);
                    }
                    return this;
                };
                Direct.INTERVAL_AUTO = 'auto';
                return Direct;
            }(econda.base.BaseClass));
            transport.Direct = Direct;
        })(transport = media.transport || (media.transport = {}));
    })(media = econda.media || (econda.media = {}));
})(econda || (econda = {}));