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="../debug.ts" />
/// <reference path="../base/BaseClass.ts" />
/// <reference path="../net/Uri.ts" />
/// <reference path="../util/ArrayUtils.ts" />
/// <reference path="./Content.ts" />
/// <reference path="./IMediaTrackerConfigOptions.ts" />
/// <reference path="./transport/Proxy.ts" />
/// <reference path="./transport/MediaEvent.ts" />
var econda;
(function (econda) {
    var media;
    (function (media) {
        var Uri = econda.net.Uri;
        var ArrayUtils = econda.util.ArrayUtils;
        var MediaEvent = econda.media.transport.MediaEvent;
        /**
         * Use one MediaTracker object for each video/audio player on your page.
         *
         *     // get tracker object and set some properties in constructor
         *     var tracker = new econda.media.MediaTracker({
         *         content: {
         *             name: "Wetten dass... - Folge 9142",
         *             category: "/Unterhaltung/Wetten dass..."
         *         },
         *         type: "video"
         *     });
         *
         *     // set one more property
         *     tracker.setDuration(150); // video length in seconds
         *
         *     // initialize it
         *     tracker.init();
         *
         *     // we would do this not here...
         *
         *     // start playback
         *     tracker.setState("playing", 0); // setState accepts the current position
         *
         *     // we could write this as...
         *     // tracker.setPosition(0).setState("playing");
         *     // but one line is more handy
         *
         *     // send user rewind
         *     tracker.setState("paused", 30);
         *     tracker.setState("playing", 5);
         *
         *     // user clicked "stop video" button
         *     tracker.setStated("stopped", 60);
         *
         *
         * @class econda.media.MediaTracker
         * @extends econda.base.BaseClass
         */
        var MediaTracker = (function (_super) {
            __extends(MediaTracker, _super);
            function MediaTracker(cfg) {
                _super.call(this);
                /**
                 * @property {Number} __instanceId Id of this tracker instance
                 * @private
                 */
                this.__instanceId = 0;
                /**
                 * True when tracker was initialized.
                 * @property {Boolean} _initialized
                 * @private
                 */
                this._initialized = false;
                /**
                 * Content object
                 * @cfg {econda.media.Content} content
                 * @accessor
                 */
                this.content = null;
                /**
                 * Media type, "audio" or "video"
                 * @cfg {String} [type="video"]
                 * @accessor
                 */
                this.type = "video";
                /**
                 * Duration in seconds
                 * @cfg {Number} duration
                 * @accessor
                 */
                this.duration = null;
                /**
                 * URI of preview video (absulte uri, including protocal, host...). Preview media files
                 * must be accessible via SSL (https://).
                 * @cfg {econda.net.Uri/string} previewUri
                 * @accessor
                 */
                this.previewUri = null;
                /**
                 * Current playback position
                 * @cfg {Number} position
                 */
                this.position = 0;
                /**
                 * Current playback state uninitialized|initialized|playing|paused|stopped
                 * @cfg {String} state
                 * @accessor
                 */
                this.state = MediaTracker.STATE_UNINITIALIZED; // uninitialized|initialized|playing|paused|stopped
                /**
                 * List of events that we've got before player was initialized. Normally that
                 * should happen only for play events.
                 * @private
                 */
                this._queuedEvents = [];
                if (cfg instanceof MediaTracker) {
                    return cfg;
                }
                this.__instanceId = MediaTracker.__instanceCount++;
                this.initConfig(cfg);
            }
            MediaTracker.prototype.getContent = function () {
                return this.content;
            };
            MediaTracker.prototype.setContent = function (content) {
                if (this.state == MediaTracker.STATE_PLAYING || this.state == MediaTracker.STATE_PAUSED) {
                    econda.debug.error("Trying to modify content information on an already playing tracker.");
                }
                else {
                    this.content = new econda.media.Content(content);
                }
                return this;
            };
            MediaTracker.prototype.getType = function () {
                return this.type;
            };
            MediaTracker.prototype.setType = function (type) {
                if (typeof type != 'string') {
                    econda.debug.error("MediaTracker.setType expects as String. Got: " + type, type);
                }
                else {
                    type = type.toLowerCase();
                    if (ArrayUtils.contains([MediaTracker.TYPE_AUDIO, MediaTracker.TYPE_VIDEO], type) === false) {
                        econda.debug.error("MediaTracker.setType expects 'audio' or 'video' as parameter. Got: " + type, type);
                    }
                    else {
                        this.type = type;
                    }
                }
                return this;
            };
            MediaTracker.prototype.getDuration = function () {
                return this.duration;
            };
            MediaTracker.prototype.setDuration = function (seconds) {
                this.duration = Number(seconds);
                return this;
            };
            MediaTracker.prototype.getPreviewUri = function () {
                return this.previewUri;
            };
            MediaTracker.prototype.setPreviewUri = function (uri) {
                var uriObj = new Uri(uri);
                if (uriObj.getScheme() !== Uri.SCHEME_HTTPS) {
                    econda.debug.error("preview uri MUST be a valid SSL uri!");
                }
                else {
                    this.previewUri = uriObj;
                }
                return this;
            };
            MediaTracker.prototype.getPosition = function () {
                return this.position;
            };
            MediaTracker.prototype.setPosition = function (seconds) {
                this.position = Number(seconds);
                return this;
            };
            MediaTracker.prototype.getState = function () {
                return this.state;
            };
            /**
             * Get used proxy instance
             * @method
             * @return {econda.media.transport.Direct}
             */
            MediaTracker.prototype.getProxy = function () {
                return econda.media.transport.Proxy.getInstance();
            };
            /**
             * Initialize tracker. Properties must be set at this point
             * @method
             */
            MediaTracker.prototype.init = function () {
                // check if we've all required data
                var ok = true;
                ok = ok && (this.content instanceof econda.media.Content && "" != this.content.getName());
                ok = ok && (this.type == MediaTracker.TYPE_AUDIO || this.type == MediaTracker.TYPE_VIDEO);
                ok = ok && (this.duration != null);
                if (ok) {
                    econda.debug.log("MediaTracker initialized.", this);
                    this.state = MediaTracker.STATE_INITIALIZED;
                    this._initialized = true;
                    this.sendQueuedEvents();
                }
                else {
                    econda.debug.error("Could not initialize MediaTracker.", this);
                }
                return this;
            };
            /**
             * Set current state and optional current position
             * @method
             * @param {String} state playing|paused|stopped
             * @param {Number} position current plaback position in seconds
             * @return {econda.media.MediaTracker}
             */
            MediaTracker.prototype.setState = function (state, position) {
                var oldState;
                // check and set new state
                if (typeof state != 'string') {
                    econda.debug.error("State value must be a string.");
                }
                else {
                    oldState = this.state;
                    state = state.toLowerCase();
                    // check for valid state values
                    if (ArrayUtils.contains(['playing', 'paused', 'stopped'], state) == false) {
                        econda.debug.error("Invalid state value given: " + state);
                    }
                    else {
                        // tracker should be initialized first
                        if (this.state == MediaTracker.STATE_UNINITIALIZED && state != MediaTracker.STATE_INITIALIZED) {
                            econda.debug.warn("Got playing/paused/stopped state changed but MediaTracker is uninitialized. Please initialize tracker first.", this);
                        }
                        this.state = state;
                        // check and set position 
                        if (typeof position != 'undefined') {
                            this.position = Number(position);
                        }
                        if (oldState != state) {
                            // Send event via proxy
                            var eventNames = {
                                playing: "play",
                                paused: "pause",
                                stopped: "stop"
                            };
                            if (this._initialized) {
                                this.sendMediaEvent(eventNames[state]);
                            }
                            else {
                                this.queueMediaEvent(eventNames[state]);
                            }
                        }
                    }
                }
                return this;
            };
            /**
             * @private
             */
            MediaTracker.prototype.queueMediaEvent = function (eventName) {
                this._queuedEvents.push(eventName);
            };
            /**
             * @private
             */
            MediaTracker.prototype.sendQueuedEvents = function () {
                for (var n = 0; n < this._queuedEvents.length; n++) {
                    this.sendMediaEvent(this._queuedEvents[n]);
                }
                this._queuedEvents = [];
            };
            /**
             * Helper to send media events using configured proxy
             * @method
             * @private
             */
            MediaTracker.prototype.sendMediaEvent = function (eventName) {
                var cmp = this, event = new MediaEvent({
                    contentLabel: cmp.getContent().toString(),
                    eventName: eventName,
                    mediaType: cmp.getType(),
                    position: Math.round(cmp.getPosition()),
                    duration: Math.round(cmp.getDuration()),
                    previewUri: cmp.getPreviewUri(),
                    trackerId: cmp.__instanceId
                });
                if (typeof this.onBeforeTrackingRequest === 'function') {
                    this.onBeforeTrackingRequest(event);
                }
                this.getProxy().sendMediaEvent(event);
            };
            /**
             * Constant value for tracker type "video"
             * @property
             * @static
             */
            MediaTracker.TYPE_VIDEO = 'video';
            /**
             * Constant value for tracker type "audio"
             * @property
             * @static
             */
            MediaTracker.TYPE_AUDIO = 'audio';
            /**
             * State when tracker was initialized.
             * @property
             * @static
             */
            MediaTracker.STATE_INITIALIZED = 'initialized';
            /**
             * State when tracker is uninitialized.
             * @property
             * @static
             */
            MediaTracker.STATE_UNINITIALIZED = 'uninitialized';
            /**
             * State when tracker is playing.
             * @property
             * @static
             */
            MediaTracker.STATE_PLAYING = 'playing';
            /**
             * State when playback is paused.
             * @property
             * @static
             */
            MediaTracker.STATE_PAUSED = 'paused';
            /**
             * State when playback is stopped.
             * @property
             * @static
             */
            MediaTracker.STATE_STOPPED = 'stopped';
            /**
             * Used to create a unique id per instance
             * @static
             * @private
             * @property {Number} [__instanceCount=0]
             */
            MediaTracker.__instanceCount = 0;
            return MediaTracker;
        }(econda.base.BaseClass));
        media.MediaTracker = MediaTracker;
    })(media = econda.media || (econda.media = {}));
})(econda || (econda = {}));