/**
 * Master Login audit panel
 *
 * @module package/quiqqer/masterlogin/bin/js/backend/controls/AuditPanel
 */
define('package/quiqqer/masterlogin/bin/js/backend/controls/AuditPanel', [
    'qui/controls/desktop/Panel',
    'controls/grid/Grid',
    'Ajax',
    'Locale',
    'css!package/quiqqer/masterlogin/bin/js/backend/controls/AuditPanel.css'
], function (Panel, Grid, QUIAjax, QUILocale) {
    'use strict';

    var lg = 'quiqqer/masterlogin';

    return new Class({
        Extends: Panel,
        Type: 'package/quiqqer/masterlogin/bin/js/backend/controls/AuditPanel',

        Binds: [
            '$onCreate',
            '$onDestroy',
            '$onResize',
            '$search',
            '$load'
        ],

        initialize: function (options) {
            this.setAttributes({
                title: QUILocale.get(lg, 'audit.panel.title'),
                icon: 'fa fa-user-secret'
            });

            this.parent(options);

            this.$Grid = null;
            this.$GridContainer = null;
            this.$Info = null;
            this.$Search = null;
            this.$SearchGroup = null;

            this.addEvents({
                onCreate: this.$onCreate,
                onDestroy: this.$onDestroy,
                onResize: this.$onResize
            });
        },

        $onCreate: function () {
            var self = this,
                Content = this.getContent();

            Content.addClass('quiqqer-masterlogin-audit');

            this.$Info = new Element('div', {
                'class': 'messages-message box message-information ' +
                    'quiqqer-masterlogin-audit__info',
                html: '<span class="fa fa-info-circle"></span><span></span>'
            }).inject(Content);

            this.$Info.querySelector('span:last-child').set(
                'text',
                QUILocale.get(lg, 'audit.panel.info')
            );

            this.$GridContainer = new Element('div', {
                'class': 'quiqqer-masterlogin-audit__grid'
            }).inject(Content);

            this.$Grid = new Grid(this.$GridContainer, {
                columnModel: [{
                    header: QUILocale.get(lg, 'audit.grid.id'),
                    dataIndex: 'id',
                    dataType: 'string',
                    width: 280
                }, {
                    header: QUILocale.get(lg, 'audit.grid.master'),
                    dataIndex: 'master',
                    dataType: 'string',
                    width: 220
                }, {
                    header: QUILocale.get(lg, 'audit.grid.slave'),
                    dataIndex: 'slave',
                    dataType: 'string',
                    width: 220
                }, {
                    header: QUILocale.get(lg, 'audit.grid.start'),
                    dataIndex: 'start',
                    dataType: 'date',
                    width: 150
                }, {
                    header: QUILocale.get(lg, 'audit.grid.end'),
                    dataIndex: 'end',
                    dataType: 'date',
                    width: 150
                }, {
                    header: QUILocale.get(lg, 'audit.grid.duration'),
                    dataIndex: 'duration',
                    dataType: 'string',
                    sortable: false,
                    width: 120
                }, {
                    header: QUILocale.get(lg, 'audit.grid.status'),
                    dataIndex: 'status',
                    dataType: 'string',
                    width: 100
                }],
                pagination: true,
                perPage: 50,
                onrefresh: this.$load,
                selectable: false,
                serverSort: true,
                sortOn: 'start',
                sortBy: 'DESC',
                buttons: [{
                    name: 'search',
                    text: QUILocale.get(lg, 'audit.search.button'),
                    textimage: 'fa fa-search',
                    events: {
                        onClick: this.$search
                    }
                }]
            });

            this.$SearchGroup = new Element('div', {
                'class': 'quiqqer-masterlogin-audit__searchGroup'
            }).inject(
                this.$GridContainer.querySelector('.tDiv [data-position="right"]'),
                'top'
            );

            this.$Search = new Element('input', {
                'class': 'quiqqer-masterlogin-audit__search',
                type: 'search',
                placeholder: QUILocale.get(lg, 'audit.search.placeholder'),
                events: {
                    keydown: function (event) {
                        if (event.key === 'enter' || event.key === 'Enter' || event.code === 13) {
                            event.stop();
                            self.$search();
                        }
                    },
                    input: function () {
                        if (!this.value) {
                            self.$search();
                        }
                    }
                }
            }).inject(this.$SearchGroup);

            this.$Grid.getButton('search').getElm()
                .addClass('quiqqer-masterlogin-audit__searchButton')
                .inject(this.$SearchGroup);

            this.$onResize();
            this.$load();
        },

        $search: function () {
            this.$Grid.setAttribute('page', 1);
            this.$load();
        },

        $load: function () {
            var self = this,
                GridParams = {
                    sortOn: this.$Grid.getAttribute('sortOn'),
                    sortBy: this.$Grid.getAttribute('sortBy'),
                    page: this.$Grid.getAttribute('page'),
                    perPage: this.$Grid.getAttribute('perPage'),
                    search: this.$Search.value.trim()
                };

            this.Loader.show();

            QUIAjax.get('package_quiqqer_masterlogin_ajax_backend_getAuditEntries', function (Result) {
                Result.data.forEach(function (Entry) {
                    Entry.status = Entry.open
                        ? QUILocale.get(lg, 'audit.status.open')
                        : QUILocale.get(lg, 'audit.status.closed');
                });

                self.$Grid.setData(Result);
                self.Loader.hide();
            }, {
                package: 'quiqqer/masterlogin',
                searchParams: JSON.encode(GridParams),
                onError: function () {
                    self.Loader.hide();
                }
            });
        },

        $onResize: function () {
            if (!this.$Grid || !this.$Info) {
                return;
            }

            var Content = this.getContent(),
                styles = window.getComputedStyle(Content),
                infoStyles = window.getComputedStyle(this.$Info),
                horizontalPadding = parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight),
                verticalPadding = parseFloat(styles.paddingTop) + parseFloat(styles.paddingBottom),
                infoHeight = this.$Info.getSize().y +
                    parseFloat(infoStyles.marginTop) + parseFloat(infoStyles.marginBottom),
                width = Content.clientWidth - horizontalPadding,
                height = Content.clientHeight - verticalPadding - infoHeight;

            this.$Grid.setHeight(Math.max(0, height - 1));
            this.$Grid.setWidth(Math.max(0, width - 1));
            this.$Grid.resize();
        },

        $onDestroy: function () {
            if (this.$Grid) {
                this.$Grid.destroy();
            }
        }
    });
});
