"use strict";

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

    MainRegionModule.VisInstanceView = MainRegionModule.ConfigGridChildView.extend({

        options: {
            state: null,
            configGrid: null,
            entityConfig: null,
            viewConfig: null,
            parentConfigGridView: null,
        },

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

            _this._configGridType = _this.options.configGrid.getType();
            _this.$el.attr("data-entity-id", _this.options.entityConfig.getClientId());
            _this.$el.attr("data-view-id", _this.options.viewConfig.getClientId());

            _this.$content = $.bem.generateElement("vis-instance", "content");
            _this.$cover   = $.bem.generateElement("vis-instance", "cover");
            _this.$coverMessage = $.bem.generateElement("vis-instance", "cover-message");
            _this.$cover.append(_this.$coverMessage);
            _this.$el.append(_this.$content, _this.$cover);

            _this._cachedEntityKind = "-";
            _this._cachedViewKind = "-";

            _this.dynamicDerivedConfigDataForEntity = null;
            _this.dynamicDerivedConfigDataForView   = null;
            _this.dynamicDerivedVisInstanceDataForBase = null;
            _this.dynamicDerivedVisInstanceDataForOverlay = null;
            _this.dynamicDerivedVisInstanceDataForTemp = null;

            _this._debouncedRenderIfParentConfigGridIsVisible = _.debounce(function() {
                _this.renderIfParentConfigGridIsVisible();
            }, 50);

            //_this.listenTo(_this.options.configGrid,   "change_selection",      _this._debouncedRenderIfParentConfigGridIsVisible);
            _this.listenTo(_this.options.entityConfig, "change:parameters",     _this._debouncedRenderIfParentConfigGridIsVisible);
            _this.listenTo(_this.options.viewConfig,   "change:parameters",     _this._debouncedRenderIfParentConfigGridIsVisible);
            _this.listenTo(_this.options.entityConfig, "change:tempParameters", _this._debouncedRenderIfParentConfigGridIsVisible);
            _this.listenTo(_this.options.viewConfig,   "change:tempParameters", _this._debouncedRenderIfParentConfigGridIsVisible);

            // Make sure that the vis is in view after click
            _this.$el.click(function() {
                var entityClientId = _this.options.entityConfig.getClientId();
                var viewClientId   = _this.options.viewConfig.getClientId();
                if (_this.options.configGrid.get("selectedEntityConfigClientId") !== entityClientId
                 || _this.options.configGrid.get("selectedViewConfigClientId")   !== viewClientId
                ) {
                    _this.options.configGrid.set({
                        selectedEntityConfigClientId: entityClientId,
                        selectedViewConfigClientId: viewClientId
                    });
                } else {
                    _this.options.parentConfigGridView.scrollAccordingToSelection();
                }
            });

        },

        remove: function() {
            var _this = this;

            if (_this.dynamicDerivedVisInstanceDataForBase) {
                _this.dynamicDerivedVisInstanceDataForBase.destroy();
            }
            if (_this.dynamicDerivedVisInstanceDataForOverlay) {
                _this.dynamicDerivedVisInstanceDataForOverlay.destroy();
            }
            if (_this.dynamicDerivedVisInstanceDataForTemp) {
                _this.dynamicDerivedVisInstanceDataForTemp.destroy();
            }
            MainRegionModule.ConfigGridChildView.prototype.remove.apply(this, arguments);
        },

        setSize: function (width, height) {
            var _this = this;
            var $el = _this.$el;
            var changed = false;
            if (width != $el.width()) {
                $el.width(width);
                changed = true;
            }
            if (height != $el.height()) {
                $el.height(height);
                changed = true;
            }

            if (changed) {
                _this._cachedSizeHash = width + "|" + height;
                _this._debouncedRenderIfParentConfigGridIsVisible();
            }
        },

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

            // do not render if view config or entity config has just been removed from the grid,
            // but the view has not been destroyed yet
            if (!this.options.entityConfig.getConfigGridType() || !this.options.viewConfig.getConfigGridType()) {
                return;
            }

            var newEntityKind = _.str.trim(_this.options.entityConfig.getParameterValue("kind"));
            var newViewKind   = _.str.trim(_this.options.viewConfig  .getParameterValue("kind"));
            var entityKindHasChanged = _this._cachedEntityKind !== newEntityKind;
            var viewKindHasChanged   = _this._cachedViewKind   !== newViewKind;

            // reassign masters
            if (entityKindHasChanged || viewKindHasChanged) {
                _this._cachedEntityKind = newEntityKind;
                _this._cachedViewKind   = newViewKind;

                if (_this.cachedViewMaster) {
                    _this.stopListening(_this.cachedViewMaster);
                }

                _this._cachedEntityMaster = App.RepresentationModule.getMasterForConfig(_this.options.entityConfig);
                _this._cachedViewMaster   = App.RepresentationModule.getMasterForConfig(_this.options.viewConfig);
                _this.$content.empty();

                _this.listenTo(_this._cachedViewMaster, "change:auxiliaryResourcesStatus", _this._debouncedRenderIfParentConfigGridIsVisible);
            }

            // change dynamic derived config data
            if (entityKindHasChanged) {
                if (_this.dynamicDerivedConfigDataForEntity) {
                    _this.stopListening(_this.dynamicDerivedConfigDataForEntity);
                }
                _this.dynamicDerivedConfigDataForEntity = App.dynamicDerivedConfigDataProvider.get(_this.options.entityConfig);
                _this.listenTo(_this.dynamicDerivedConfigDataForEntity, "change", _this._debouncedRenderIfParentConfigGridIsVisible);
            }

            if (viewKindHasChanged) {
                if (_this.dynamicDerivedConfigDataForView) {
                    _this.stopListening(_this.dynamicDerivedConfigDataForView);
                }
                _this.dynamicDerivedConfigDataForView = App.dynamicDerivedConfigDataProvider.get(_this.options.viewConfig);
                _this.listenTo(_this.dynamicDerivedConfigDataForView, "change", _this._debouncedRenderIfParentConfigGridIsVisible);
            }

            // change dynamic derived vis instance data
            if (entityKindHasChanged || viewKindHasChanged) {
                var dynamicDataTypes = ["Base", "Overlay", "Temp"];
                for (var i = 0; i < 3; i++) {
                    var propertyName          = "dynamicDerivedVisInstanceDataFor" + dynamicDataTypes[i];
                    var generatorFunctionName = "generateDynamicDerivedVisInstanceDataFor" + dynamicDataTypes[i];
                    if (_this[propertyName]) {
                        _this.stopListening(_this[propertyName]);
                        _this[propertyName].destroy();
                    }
                    _this[propertyName] = _this._cachedEntityMaster[generatorFunctionName](_this);
                    _this.listenTo(_this[propertyName], "change", _this._debouncedRenderIfParentConfigGridIsVisible);
                }
            }

            _this._cachedViewMaster.renderVisInstance(_this, deep, instant);
        },

        cancelPointerHighlights: function() {
            var _this = this;
            if (_this._cachedViewMaster) {
                _this._cachedViewMaster.cancelVisInstancePointerHighlights(_this);
            }
        },
    });
}, Logger);