"use strict";
App.module("PlayerModule", function(PlayerModule, App, Backbone, Marionette, $, _, Logger) {
    // Prevent auto start
    PlayerModule.startWithParent = false;

    // Define options
    var defaultModuleOptions = {
    };
    var moduleOptions;

    // Define private variables
    var logger = null;

    /**
     * Initialization checker
     */
    var assertModuleIsInitialized = function() {
        if (!$notifications) {
            throw "PlayerModule has not been initialized";
        }
    };

    /**
     * Module initializer
     *
     */
    PlayerModule.addInitializer(function(options){
        moduleOptions = _.extend(defaultModuleOptions, options);

        logger = Logger.get("PlayerModule");
        //logger.setLevel(Logger.DEBUG);

        logger.debug("Begin init");

        PlayerModule.$player = $(Marionette.TemplateCache.get("#player")());
        PlayerModule.$playerTimeAfter = PlayerModule.$player.find(".player__time_type_after");
        PlayerModule.$player.hide().appendTo("body");

        PlayerModule.$jPlayer = $("<div/>").hide().appendTo("body");

        var volume = App.DataModule.Storage.getStrCache(PlayerModule, "volume");
        if (volume !== undefined) {
            volume = parseFloat(volume);
        }
        if (!_.isNumber(volume) || _.isNaN(volume) || volume < 0 && volume > 1) {
            volume = undefined;
        }
        var muted = App.DataModule.Storage.getStrCache(PlayerModule, "muted") ? true : false;

        // The player itself (jPlayer)
        PlayerModule.$jPlayer.jPlayer({
            swfPath: "./$/jquery.jplayer.swf",
            supplied: "mp3",
            wmode: "window",
            cssSelectorAncestor: '.player__body',
            useStateClassSkin: true,
            autoBlur: false,
            smoothPlayBar: false,
            keyEnabled: false,
            remainingDuration: true,
            toggleDuration: false,
            volume: volume,
            solution: "html,flash",
            muted: muted,
            cssSelector: {
                play:           ".player__command_action_play",
                pause:          ".player__command_action_pause",
                mute:           ".player__command_action_volume-mute",
                unmute:         ".player__command_action_volume-down",
                volumeMax:      ".player__command_action_volume-up",
                volumeBar:      ".player__slider_type_volume",
                volumeBarValue: ".player__slider-head_type_volume",
                seekBar:        ".player__slider_type_time",
                playBar:        ".player__slider-head_type_time",
                currentTime:    ".player__time_type_before",
                duration:       ".player__time_type_after",
            }
        });

        PlayerModule.$jPlayer.on($.jPlayer.event.volumechange, function(event) {
            var volume = PlayerModule.$jPlayer.jPlayer('option', 'volume');
            var muted = PlayerModule.$jPlayer.jPlayer('option', 'muted');

            App.DataModule.Storage.setStrCache(PlayerModule, "volume", volume + "");
            App.DataModule.Storage.setStrCache(PlayerModule, "muted", muted ? "1" : "");

        });

        // A view that sits on top of the player
        PlayerModule.PlayerView = Backbone.View.extend({

            el: PlayerModule.$player,

            initialize: function() {
                var _this = this;
                //var $elHTML = $("#player");
                _this.$body = _this.$el.find('.player__body');
                App.TooltipModule.convertTitlesToTooltips(_this.$el);

                // This is needed to initialize the jplayer instance
                //$elHTML.hide().appendTo("body");

                //_this.$el.html($elHTML);
                //$elHTML.show();
                _this.$el.show();

                _this.$commandDownload = _this.$('.player__command_action_download');
                _this.$commandDownload.click(function(event) {
                    PlayerModule.$jPlayer.jPlayer("pause");
                });
                _this.$label1 = _this.$('.player__label_row_1');
                _this.$label2 = _this.$('.player__label_row_2');

                _this.$cover = _this.$('.player__cover');
                _this.$messageError = _this.$('.player__message_type_error');
                _this.$messageLoading = _this.$('.player__message_type_loading');
                _this.$messageNoRecording = _this.$('.player__message_type_no-recording');
                _this.$messageNoAudio = _this.$('.player__message_type_no-audio');

                _this._startPlayingAfterRecordingIsLoaded = false;

                _this._config = new App.ContextModule.Config();
                _this._dynamicDefinitionForRecording = App.dynamicDefinitionProviderForRecordings.get(_this._config);

                _this.listenTo(_this._dynamicDefinitionForRecording, "change", _this.render);
                _this.listenTo(_this._config, "change", _this.render);



                this._cachedLabel = "initial";
                _this.render();
            },

            render: function() {
                var _this = this;
                var recordingAttributes = _this._dynamicDefinitionForRecording.attributes;
                var label = recordingAttributes.label;
                var audio = recordingAttributes.audio ? recordingAttributes.audio[0] : undefined;

                // Update layout
                if (!_.isEqual(_this._cachedRecordingAttributes, recordingAttributes)) {
                    if (!_this._dynamicDefinitionForRecording.attributes.label || !audio) {
                        _this.$body.hide();
                        _this.$cover.show();
                        _this.$cover.children().hide();
                        switch (label) {
                        case false:
                            _this.$messageError.show();
                            break;
                        case null:
                            _this.$messageLoading.show();
                            break;
                        default:
                            if (label === undefined) {
                                _this.$messageNoRecording.show();
                            } else {
                                _this.$messageNoAudio.show();
                            }
                        }
                        PlayerModule.$jPlayer.jPlayer("stop");
                    } else {

                        PlayerModule.$jPlayer.jPlayer("setMedia", {
                            mp3: audio,
                        });

                        _this.$cover.hide();
                        _this.$body.show();
                        _this.$label1.text(recordingAttributes.label);
                        _this.$label2.text(recordingAttributes.composer);
                        _this.$commandDownload.attr("href", audio);

                        if (_this._startPlayingAfterRecordingIsLoaded) {
                            PlayerModule.$jPlayer.jPlayer("play");
                            _this._startPlayingAfterRecordingIsLoaded = false;
                        }

                    }
                }

                if (label) {

                }
                _this._cachedRecordingAttributes = recordingAttributes;
            },

            play: function(recordingURI, time) {
                var _this = this;
                if (_this._config.getParameterValue("recordingURI") != recordingURI) {
                    _this._startPlayingAfterRecordingIsLoaded = true;
                    _this._config.updateParameter("recordingURI", recordingURI);
                } else {
                    PlayerModule.$jPlayer.jPlayer("play", time ? time : 0);
                }
            },

            stop: function(recordingURI) {
                var _this = this;
                PlayerModule.$jPlayer.jPlayer("pause");
            }
        });


        PlayerModule.playerView = new PlayerModule.PlayerView();
    });

    PlayerModule.play = function(recordingURI, time) {
//        try {
            PlayerModule.playerView.play(recordingURI, time);
//        } catch (e) {
//            console.log(e);
//        }
        App.NotificationsModule.show({
            id: "player",
            content: PlayerModule.playerView.$el,
            onClose: function() {PlayerModule.playerView.stop();},
            modifiers: ["ttl_ever", "no-padding"],
            keepContentInMemoryAfterRemoval: true
        });
    };

}, Logger);
