import { eqi18n, EqContext, DataModel, Query } from '@easyquery/core' 


export function registerFilterBarWidget($) {

    $.widget("eqjs.FilterBar", {
        _queryPanelWidget: null,
        _query : null,
        _queryIsChanged: false,

        _headerElement: null,
        _headerIconElement: null,
        _headerTextBlock: null,
        _headerTextElement: null,
        _headerLinkElement: null,
        _headerArrowBlock: null,
        _headerArrowElement: null,
        _qpBlock: null,
        _qpElement: null,

        _buttonsBlock: null,
        _btnApply: null,
        _btnClear: null,

        _context: null,

        options: {
            applyOnClose: true,

            showApplyButton: true,

            showClearButton: true,

            applyFilterCallback: null,

            queryPanel: {
                showAddRow: true,
                showCheckboxes: true,
                alwaysShowButtonsInPredicates: true
            }
        },

        getQuery: function () {
            return this._query;
        },

        setQuery: function (query) {
            if (this._query) {
                this._query.removeChangedCallback($.proxy(this._queryChangedHandler, this)); //removing old query observer
            }
            this._query = query;
            this._query.addChangedCallback($.proxy(this._queryChangedHandler, this));
            this._queryIsChanged = true;

            this._qpElement.QueryPanel("setQuery", this._query);

            this._updateHeader();
        },

        setContext: function (context: EqContext) {
            this._context = context;

            this._qpElement.QueryPanel("setContext", this._context);
        },

        getContext: function() {
            return this._context;
        },

        _showQueryPanel: function (func) {
            var self = this;

            self._qpBlock.slideDown(400, function () {
                self._updateHeader();
                if (func) {
                    func();
                }
            });
        },

        _hideQueryPanel: function () {
            var self = this;
            self._qpBlock.slideUp(400, function () {
                self._qpBlock.hide();
                self._updateHeader();

                if (self.options.applyOnClose) {
                    self.applyFilter();
                }

            });
        },

        applyFilter: function (applyForcibly) {
            if (this._queryIsChanged || applyForcibly == true) {
                if (this.options.applyFilterCallback) {
                    this.options.applyFilterCallback();
                    this._queryIsChanged = false;
                }
            }
        },

        clearFilter: function () {
            if (this._query) {
                this._query.clearConditions();
            }
        },

        _queryChangedHandler: function (event) {
            this._updateHeader();
            this._queryIsChanged = true;

            if (event.data && event.data.changeType == "condition.add" && this.options.autoEditNewCondition) {
                this._queryPanelWidget.editConditionValue(event.data.condition);
            }
        },

        _headerClickHandler: function () {
            var self = this;
            if (self._qpBlock.is(':visible')) {  // close query panel
                self._hideQueryPanel();
            }
            else {  //open query panel
                self._showQueryPanel();
            }
        },

		_cssPwby: function (pwdbylnk) {
			pwdbylnk.css({
				'color': 'white',
				'font': '11px Calibri',
				'position': 'absolute',
				'top': '-16px',
				'right': '31px'
			});
		},
		
        _create: function () {
            var self = this;

            this.element.addClass('eqjs-fb-container');
            this._headerElement = $('<div></div>')
                .addClass('eqjs-fb-header');
            this.element.append(this._headerElement);

            this._headerIconElement = $('<div></div>')
                .addClass('eqjs-fb-header-icon');
            this._headerElement.append(this._headerIconElement);

            this._headerTextBlock = $('<div></div>')
                .addClass('eqjs-fb-header-textblock');
            this._headerElement.append(this._headerTextBlock);

            this._headerTextElement = $('<span></span>')
                .addClass('eqjs-fb-header-text');
            this._headerTextBlock.append(this._headerTextElement);

            this._headerLinkElement = $('<a href="javascript:void(0)">' + eqi18n.getText('StrNoFilterClickToAdd') + '</a>')
                .addClass('eqjs-fb-header-link')
                .hide()
                .click(function () {
                    const context = self._context as EqContext;

                    context.getBroker().getModelPromise().then((dm: DataModel) => {

                        self._queryPanelWidget.showEntitiesMenu({
                            anchor: self._headerLinkElement,
                            selectedIds: null,
                            itemSelectedCallback: function (evt, data) {
                                var attrid = data.menuItem.data('id');

                                self._showQueryPanel(function () {
                                    self._queryPanelWidget.addNewCondition(attrid);
                                });
                            }
                        });
                    });
                    
                });

            this._headerTextBlock.append(this._headerLinkElement);

            /// Up/Down arrow
            this._headerArrowBlock = $('<div></div>')
                .addClass('eqjs-fb-header-arrowblock');
            this._headerElement.append(this._headerArrowBlock);

            this._headerArrowElement = $('<div></div>')
                .addClass('eqjs-fb-header-arrow');
            this._headerArrowBlock.append(this._headerArrowElement);

            /// QueryPanel block
            this._qpBlock = $('<div></div>').hide();
            this._qpBlock.addClass('eqjs-fb-querypanelblock');
            this.element.append(this._qpBlock);

            /// QueryPanel
            
            this._qpElement = $('<div></div>');
            this._qpElement.addClass('query-panel eqjs-fb-querypanel');
            this._qpElement.QueryPanel(this.options.queryPanel);
            this._qpElement.QueryPanel("setQuery", this._query);
            this._qpBlock.append(this._qpElement);

            this._queryPanelWidget = this._qpElement.data('QueryPanel'); //jQuery before 1.9
            if (!this._queryPanelWidget) {
                this._queryPanelWidget = this._qpElement.data('eqjs-QueryPanel'); //jQuery after 1.9
            }
			
			this._queryPanelWidget._cssPwby = this._cssPwby;
			

            /// Buttons
            if (this.options.showApplyButton || this.options.showClearButton) {
                this._buttonsBlock = $('<div></div>')
                    .addClass('eqjs-fb-buttonsblock');
                this._qpBlock.append(this._buttonsBlock);
            }

            if (this.options.showApplyButton) {
                this._btnApply = $('<a href="javascript:void(0)"></a>')
                    .addClass('eqjs-fb-button eqjs-fb-button-apply')
                    .text(eqi18n.getText('ButtonApply'))
                    .on('click', $.proxy(this.applyFilter, this));
                this._buttonsBlock.append(this._btnApply);
            }

            if (this.options.showClearButton) {
                this._btnClear = $('<a href="javascript:void(0)"></a>')
                    .addClass('eqjs-fb-button eqjs-fb-button-clear')
                    .text(eqi18n.getText('ButtonClear'))
                    .on('click', $.proxy(this.clearFilter, this));
                this._buttonsBlock.append(this._btnClear);
            }

            $(window).resize(function () {
                self.textResize(self);
            });

            setTimeout(function () { self.textResize(self); }, 500);

            this._render();
        },

        textResize: function (self) {
            if (!self) {
                self = this;
            }
            self._headerTextBlock.css("width", self.element.width() - self._headerIconElement.outerWidth(true) - (self._headerArrowBlock.is(':visible') ? self._headerArrowBlock.outerWidth(true) : 0) + "px");
        },

        _render: function () {
            var self = this;

            this._headerIconElement.empty();

            this._updateHeader();
            this._qpElement.QueryPanel("refresh");

            this.textResize(self);
        },

        refresh: function () {
            this._render();
        },

        _updateHeader: function () {
            var text = '';

            if (this._query) {
                text = (this._query as Query).getConditionsText();
            }
            
            /*
			try {
				text = (this._query as Query).getConditionsText();
			}
            catch {}
            */
			
            if (text == '') {
                text = eqi18n.getText('StrNoFilterDefined');
            }
            this._headerTextElement.text(text).attr('title', text);

            if (!this._query || this._query.isEmptyConditions()) {  //empty query, don't show query panel and arrow, show link in header
                this._headerTextElement.hide();
                this._headerLinkElement.show();
                if (!this._qpBlock.is(':visible')) {
                    this._headerArrowBlock.hide();
                    this._headerElement
                        .off('click.FilterBar')
                        .css('cursor', '');
                }
            }
            else {
                this._headerElement
                    .off('click.FilterBar')
                    .on('click.FilterBar', $.proxy(this._headerClickHandler, this))
                    .css('cursor', 'pointer');

                this._headerTextElement.show();
                this._headerLinkElement.hide();
                this._headerArrowBlock.show();
            }

            if (this._qpBlock.is(':visible')) {  // close query panel
                this._headerArrowElement.addClass('eqjs-fb-header-arrowUp');
            }
            else {
                this._headerArrowElement.removeClass('eqjs-fb-header-arrowUp');
            }

            this.textResize(this);
        }


    });
}