/**
 * Slave user Select for Master Login
 *
 * @module package/quiqqer/UserSelectPopup/bin/js/frontend/controls/UserSelectPopup
 * @author www.pcsg.de (Patrick Müller)
 *
 * @event onUserSelect [userId, this] - Fires if the user selects a user from the list
 */
define('package/quiqqer/masterlogin/bin/js/frontend/controls/UserSelectPopup', [

    'qui/QUI',
    'qui/controls/windows/SimpleConfirmWindow',
    'qui/controls/buttons/Button',

    'package/quiqqer/masterlogin/bin/js/frontend/Manager',

    'controls/grid/Grid',
    'Locale',
    'Ajax',
    'Mustache',

    'text!package/quiqqer/masterlogin/bin/js/frontend/controls/UserSelectPopup.html',
    'css!package/quiqqer/masterlogin/bin/js/frontend/controls/UserSelectPopup.css'

], function (QUI, QUISimpleConfirmWindow, QUIButton, MasterLoginManager, Grid, QUILocale, QUIAjax, Mustache, template) {
    "use strict";

    var lg = 'quiqqer/masterlogin';

    return new Class({

        Extends: QUISimpleConfirmWindow,
        Type: 'package/quiqqer/UserSelectPopup/bin/js/frontend/controls/UserSelectPopup',

        Binds: [
            '$onOpen',
            '$listRefresh',
            '$onUserSelect',
            '$updateSubmitButtonState'
        ],

        options: {
            'class': 'quiqqer-masterlogin-userselect',
            maxHeight: 800,
            maxWidth: 1000,
            autoclose: false,
            contentPadding: true,
            buttonSubmit: {
                'class': 'btn btn-primary',
                'icon': 'fa fa-sign-in',
                'text': QUILocale.get(lg, 'controls.UserSelectPopup.btn.submit'),
            },
            buttonCancel: {
                'class': 'btn btn-link-body',
                'icon': false,
                'text': QUILocale.get(lg, 'controls.UserSelectPopup.closeButtonText'),
            }
        },

        initialize: function (options) {
            this.parent(options);

            this.$Content = null;
            this.$Grid = null;
            this.$SearchInput = null;
            this.$SubmitBtn = null;

            this.addEvents({
                onOpen: this.$onOpen,
                onSubmit: this.$onUserSelect
            });
        },

        /**
         * Event: onOpen
         */
        $onOpen: function () {
            var self = this;

            // Build content
            var Content = this.getContent();

            Content.set('html', Mustache.render(template, {
                title: QUILocale.get(lg, 'controls.UserSelectPopup.title'),
                searchPlaceholder: QUILocale.get(lg, 'controls.UserSelectPopup.tpl.searchPlaceholder'),
                searchLabel: QUILocale.get(lg, 'controls.UserSelectPopup.tpl.searchLabel')
            }));

            this.$SubmitBtn = this.getElm().querySelector('button[name="submit"]');
            this.getElm().querySelector('button[name="close"]').setAttribute(
                'aria-label',
                QUILocale.get(lg, 'controls.UserSelectPopup.closeButtonText')
            );
            this.$updateSubmitButtonState();

            this.$SearchInput = Content.getElement('.quiqqer-masterlogin-userselect-search input');

            this.$SearchInput.addEvent('keyup', function (event) {
                if (event.key === 'enter' || self.$SearchInput.value === '') {
                    self.$Grid.refresh();
                }
            });

            new QUIButton({
                'title': QUILocale.get(lg, 'controls.UserSelectPopup.btn.runSearch'),
                icon: 'fa fa-search',
                events: {
                    onClick: function () {
                        self.$Grid.refresh();
                    }
                }
            }).inject(Content.getElement('.quiqqer-masterlogin-userselect-search__inputWrapper'));

            // Build Grid
            var GridParent = Content.getElement('.quiqqer-masterlogin-userselect-table');

            this.$Grid = new Grid(GridParent, {
                columnModel: [{
                    header: QUILocale.get('quiqqer/system', 'id'),
                    dataIndex: 'id',
                    dataType: 'number',
                    width: 100
                }, {
                    header: QUILocale.get(lg, 'controls.UserSelectPopup.tbl.header.name'),
                    dataIndex: 'name',
                    dataType: 'string',
                    width: 200
                }, {
                    header: QUILocale.get(lg, 'controls.UserSelectPopup.tbl.header.email'),
                    dataIndex: 'email',
                    dataType: 'string',
                    width: 200
                }, {
                    header: QUILocale.get(lg, 'controls.UserSelectPopup.tbl.header.company'),
                    dataIndex: 'company',
                    dataType: 'string',
                    width: 250
                }, {
                    dataIndex: 'uuid',
                    dataType: 'string',
                    hidden: true
                }],
                pagination: true,
                serverSort: true,
                selectable: true,
                multipleSelection: false
            });

            this.$Grid.addEvents({
                onDblClick: function () {
                    self.$updateSubmitButtonState();

                    if (self.$Grid.getSelectedData().length) {
                        self.submit();
                    }
                },
                onClick: function () {
                    self.$updateSubmitButtonState();
                },
                onRefresh: this.$listRefresh
            });

            var size = GridParent.getSize();

            this.$Grid.setHeight(size.y);
            this.$Grid.resize();

            this.$Grid.refresh();

            this.$SearchInput.focus();
        },

        $updateSubmitButtonState: function () {
            if (!this.$SubmitBtn) {
                return;
            }

            this.$SubmitBtn.disabled = !this.$Grid || !this.$Grid.getSelectedData().length;
        },

        /**
         * Sign-in as slave user
         */
        $onUserSelect: function () {
            if (!this.$Grid || !this.$Grid.getSelectedData().length) {
                return;
            }

            var userUuid = this.$Grid.getSelectedData()[0].uuid;
            this.fireEvent('userSelect', [userUuid, this]);
        },

        /**
         * Refresh user list
         *
         * @param {Object} Grid
         */
        $listRefresh: function (Grid) {
            if (!this.$Grid) {
                return;
            }

            var self = this;

            this.$updateSubmitButtonState();

            var GridParams = {
                sortOn: Grid.getAttribute('sortOn'),
                sortBy: Grid.getAttribute('sortBy'),
                perPage: Grid.getAttribute('perPage'),
                page: Grid.getAttribute('page')
            };

            this.Loader.show();

            var searchTerm = this.$SearchInput.value.trim();

            if (searchTerm !== '') {
                GridParams.search = searchTerm;
            }

            MasterLoginManager.searchUsers(GridParams).then(function (ResultData) {
                self.Loader.hide();

                if (ResultData) {
                    self.$Grid.setData(ResultData);
                    self.$updateSubmitButtonState();
                }
            });
        }
    });
});
