/**
 * 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/Popup',
    '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, QUIPopup, QUIButton, MasterLoginManager, Grid, QUILocale, QUIAjax, Mustache, template) {
    "use strict";

    var lg = 'quiqqer/masterlogin';

    return new Class({

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

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

        options: {
            'class': 'quiqqer-masterlogin-userselect',
            maxHeight: 800,
            title: QUILocale.get(lg, 'controls.UserSelectPopup.title'),
            closeButtonText: QUILocale.get(lg, 'controls.UserSelectPopup.closeButtonText'),
            icon: 'fa fa-sign-in'
        },

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

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

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

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

            // Buttons
            this.$SubmitBtn = new QUIButton({
                text: QUILocale.get(lg, 'controls.UserSelectPopup.btn.submit'),
                textimage: 'fa fa-sign-in',
                events: {
                    onClick: this.$onUserSelect
                }
            });

            this.addButton(this.$SubmitBtn);

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

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

            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.fireEvent('select', [self.$Grid.getSelectedData()[0].id, self]);
                },
                onClick: function () {
                    var selected = self.$Grid.getSelectedData().length;

                    if (selected.length) {
                        self.$SubmitBtn.disable();
                        return;
                    }

                    self.$SubmitBtn.enable();
                },
                onRefresh: this.$listRefresh
            });

            var size = GridParent.getSize();

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

            this.$Grid.refresh();

            this.$SearchInput.focus();
        },

        /**
         * Sign-in as slave user
         */
        $onUserSelect: function () {
            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.$SubmitBtn.disable();

            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);
                }
            });
        }
    });
});