"use strict";

App.module("MainRegionModule", function (MainRegionModule, App, Backbone, Marionette, $, _, Logger) {

    MainRegionModule.ConfigGridPanelView = MainRegionModule.ConfigGridChildView.extend({

        options: {
            dimension: null, // entity | view
            configGrid: null,
            parentState: null,
            parentConfigGridView: null
        },

        _cachedConfigGridType: null,
        _cachedConfig: null,
        _cachedBorderRadiusFixerSize: null,

        initialize: function(options) {
            var _this = this;
            _this.options = _.defaults(options || {}, this.options);;

            _this.listenTo(_this.options.configGrid, "change_selection", _this.renderIfParentConfigGridIsVisible);

            // Cached attributes
            _this._cachedConfigGridType = this.options.configGrid.getType();

            // Init border radius fixer (sits under the background and fills white space if the currently selected entity / view is near the corner)
            _this._$borderRadiusFixer = $.bem.generateElement("config-grid-panel", "border-radius-fixer");
            _this._$borderRadiusFixerContainer = $.bem.generateElement("config-grid-panel", "border-radius-fixer-container");
            _this._$borderRadiusFixerContainer.append(_this._$borderRadiusFixer);
            _this.$el.prepend(_this._$borderRadiusFixerContainer);
            _this._cachedBorderRadiusFixerSize = _this._$borderRadiusFixerContainer.width();
            _this.updateRadiusFixer(null, null);

            // Init main area
            _this._$mainAreaWrapper = $.bem.generateElement("config-grid-panel", "main-area-wrapper");
            _this._$mainArea = $.bem.generateElement("config-grid-panel", "main-area");
            _this._$mainArea.addClass("cgpma"); // this element is also a block
            _this._$mainArea.appendTo(_this._$mainAreaWrapper);
            _this._$mainAreaWrapper.appendTo(_this.$el);

            // Init commands
            _this._$commands = _this.$(".config-grid-panel__commands");
            _this._$commandClone   = _this.$(".config-grid-panel__command_action_clone");
            _this._$commandDelete  = _this.$(".config-grid-panel__command_action_delete");
            _this._$commandApply   = _this.$(".config-grid-panel__command_action_apply");
            _this._$commandDiscard = _this.$(".config-grid-panel__command_action_discard");

            // Assign functions to the commands
            _this._$commandClone.click(function() {
                if (_this._cachedConfig && _this._$commandClone.hasClass("config-grid-panel__command_state_enabled")) {
                    var clonedConfig = _this._cachedConfig.clone();
                    if (_this.options.dimension == "entity") {
                        _this.options.configGrid.addEntityAndSelectIt(clonedConfig, _this.options.configGrid.getNextEntityNeighbour(_this._cachedConfig));
                    } else {
                        _this.options.configGrid.addViewAndSelectIt(clonedConfig, _this.options.configGrid.getNextViewNeighbour(_this._cachedConfig));
                    }
                }
            });
            _this._$commandDelete.click(function() {
                if (_this._cachedConfig && _this._$commandDelete.hasClass("config-grid-panel__command_state_enabled")) {
                    if (_this.options.dimension == "entity") {
                        _this.options.configGrid.removeEntityAndSelectNeighbour(_this._cachedConfig);
                    } else {
                        _this.options.configGrid.removeViewAndSelectNeighbour(_this._cachedConfig);
                    }
                }
            });

            _this._$commandApply.click(function() {
                if (_this._cachedConfig && _this._$commandApply.hasClass("config-grid-panel__command_state_enabled")) {
                    _this._masterBehindMainArea.cleanConfigPlannedParameterValuesAndApplyThem(_this._cachedConfig);
                }
            });

            _this._$commandDiscard.click(function() {
                if (_this._cachedConfig && _this._$commandDiscard.hasClass("config-grid-panel__command_state_enabled")) {
                    _this._cachedConfig.cancelPlannedParameterUpdates();
                }
            });

            _this._$commandClone  .attr("title", " ");
            _this._$commandDelete .attr("title", " ");
            _this._$commandApply  .attr("title", " ");
            _this._$commandDiscard.attr("title", " ");
            App.TooltipModule.convertTitlesToTooltips(_this.$el);
            _this._updateTooltips();

            _this._$commands.disableSelection();
        },

        render: function (deep, instant) {
            var _this = this;

            var selectedConfig = null;
            if (_this.options.dimension == "entity") {
                selectedConfig = _this.options.configGrid.getSelectedEntityConfig();
            } else {
                selectedConfig = _this.options.configGrid.getSelectedViewConfig();
            }

            var configWasReplaced = false;
            if (_this._cachedConfig != selectedConfig) {

                if (_this._cachedConfig) {
                    _this.stopListening(_this._cachedConfig, "change", _this.renderIfParentConfigGridIsVisible);
                };

                _this._cachedConfig = selectedConfig;

                if (_this._cachedConfig) {
                    _this.listenTo(_this._cachedConfig, "change", _this.renderIfParentConfigGridIsVisible);
                };

                configWasReplaced = true;
                _this._updateTooltips();
            }

            var dynamicDerivedConfigData = App.dynamicDerivedConfigDataProvider.get(_this._cachedConfig);
            if (_this._cachedDynamicDerivedConfigData != dynamicDerivedConfigData) {
                if (_this._cachedDynamicDerivedConfigData) {
                    this.stopListening(_this._cachedDynamicDerivedConfigData, "change", _this.renderIfParentConfigGridIsVisible);
                }

                _this._cachedDynamicDerivedConfigData = dynamicDerivedConfigData;

                if (_this._cachedDynamicDerivedConfigData) {
                    _this.listenTo(_this._cachedDynamicDerivedConfigData, "change", _this.renderIfParentConfigGridIsVisible);
                };
            }

            _this._setupMainArea(deep, instant);

            var hashForData = null;
            if (_this._cachedConfig) {
                hashForData = _this._cachedConfig.getHash()
                    + _this._cachedDynamicDerivedConfigData.getHash();
            }
            if (configWasReplaced || _this._cachedHashForData !== hashForData) {
                _this._cachedHashForData = hashForData;
                if (_this._masterBehindMainArea) {
                    _this._masterBehindMainArea.syncConfigGridPanelMainArea(_this, instant);
                }
                _this._renderApplyDiscardCommands(deep, instant);
            }

            if (configWasReplaced || deep) {
                _this._renderCloneDeleteCommands(deep, instant);
            }
        },

        updateRadiusFixer: function(selectedConfigGridOffsetStart, selectedConfigGridSize) {
            var _this = this;
            var coordinate = selectedConfigGridOffsetStart;
            var size = selectedConfigGridSize;

            if (_.isNumber(size) && !_.isNaN(size) && size > 0) {
                if (coordinate + size <= 0) {
                    coordinate = null;
                }
                if (coordinate > _this._cachedBorderRadiusFixerSize) {
                    coordinate = null;
                } else if (coordinate < 0) {
                    coordinate = 0;
                } else if (coordinate + size > _this._cachedBorderRadiusFixerSize) {
                    size = _this._cachedBorderRadiusFixerSize - coordinate;
                }
            } else {
                coordinate = null;
                size = null;
            }
            if (coordinate !== null) {
                if (_this.options.dimension == "entity") {
                    _this._$borderRadiusFixer.css({"left": coordinate, "width": size});
                } else {
                    _this._$borderRadiusFixer.css({"top": coordinate, "height": size});
                }
            } else {
                if (_this.options.dimension == "entity") {
                    _this._$borderRadiusFixer.css({"left": 0, "width": 0});
                } else {
                    _this._$borderRadiusFixer.css({"top": 0, "height": 0});
                }
            }
        },

        _updateTooltips: function() {
            var _this = this;
            if (! this._cachedConfig) {
                _this._$commandClone  .attr("tooltip-title", "");
                _this._$commandDelete .attr("tooltip-title", "");
                _this._$commandApply  .attr("tooltip-title", "");
                _this._$commandDiscard.attr("tooltip-title", "");
            } else {
                var tooltipTemplate = null;
                try {
                    tooltipTemplate = Marionette.TemplateCache.get("#config-grid-panel__command-titles_" + _this._cachedConfigGridType + "_" + this._cachedConfig.getDimension() + "_" + _.str.trim(this._cachedConfig.getParameterValue("kind")));
                } catch (e) {
                    tooltipTemplate = Marionette.TemplateCache.get("#config-grid-panel__command-titles_" + _this._cachedConfigGridType + "_" + this._cachedConfig.getDimension());
                }
                var tooltips = tooltipTemplate().split("|");
                _this._$commandClone  .attr("tooltip-title", tooltips[0]);
                _this._$commandDelete .attr("tooltip-title", tooltips[1]);
                _this._$commandApply  .attr("tooltip-title", tooltips[2]);
                _this._$commandDiscard.attr("tooltip-title", tooltips[3]);
            }
        },

        _renderCloneDeleteCommands: function(deep, instant) {
            var _this = this;
            //var cloneEnabled  = !!(_this._cachedConfig && !(_this.options.dimension == "entity" && _this._cachedConfigGridType == "recording"));
            var cloneEnabled  = !! _this._cachedConfig;
            var deleteEnabled = !! _this._cachedConfig;
            _this._$commandClone .toggleClass("config-grid-panel__command_state_enabled", cloneEnabled);
            _this._$commandDelete.toggleClass("config-grid-panel__command_state_enabled", deleteEnabled);
        },

        _renderApplyDiscardCommands: function(deep, instant) {
            var _this = this;
            var enabled = !!(_this._cachedConfig && _this._cachedConfig.hasPlannedParameterUpdates());
            _this._$commandApply  .toggleClass("config-grid-panel__command_state_enabled", enabled);
            _this._$commandDiscard.toggleClass("config-grid-panel__command_state_enabled", enabled);
        },



        _setupMainArea: function(deep, instant) {
            var _this = this;

            var master = null;
            if (_this._cachedConfig) {
                master = App.RepresentationModule.getMasterForConfig(_this._cachedConfig, true);
            }

            var configHasChanged = _this._configBehindMainArea !== _this._cachedConfig;
            var masterHasChanged = _this._masterBehindMainArea !== master;

            if (configHasChanged || masterHasChanged) {
                if (_this._masterBehindMainArea) {
                    _this._masterBehindMainArea.destroyConfigGridPanelMainArea(this);
                }

                if (!_this._cachedConfig) {
                    _this._configBehindMainArea = null;
                    _this._masterBehindMainArea = null;
                    _this._$mainArea.html(Backbone.Marionette.TemplateCache.get("#cgpma_" + _this._cachedConfigGridType + "_" + this.options.dimension + "__empty"));
                } else {

                    _this._configBehindMainArea = _this._cachedConfig;
                    _this._masterBehindMainArea = master;

                    _this._$mainArea.empty();
                    _this._$mainArea.removeData();

                    try {
                        _this._$mainArea.html(Backbone.Marionette.TemplateCache.get("#cgpma_" + _this._cachedConfigGridType + "_" + this.options.dimension + "_" + master.id.split(".")[2]));
                    } catch (e) {
                        _this._$mainArea.html(Backbone.Marionette.TemplateCache.get("#cgpma_" + _this._cachedConfigGridType + "_" + this.options.dimension + "__unknown"));
                    }
                    _this._masterBehindMainArea.prepareConfigGridPanelMainArea(_this);
                }

                var masterKind = undefined;
                if (_this._masterBehindMainArea) {
                    masterKind = _this._masterBehindMainArea.id.split(".")[2];
                }
                this.$el.setMod("config-grid-panel", "master-kind", masterKind ? masterKind : false);
            }
        },
    });
}, Logger);