/**
 * Info popup manager panel.
 *
 * Lists and manages the info popup entries of a project.
 *
 * @module package/quiqqer/info-popup/bin/controls/Manager
 * @author www.pcsg.de
 */
define('package/quiqqer/info-popup/bin/controls/Manager', [

    'qui/QUI',
    'qui/controls/desktop/Panel',
    'qui/controls/buttons/Separator',
    'qui/controls/windows/Confirm',
    'controls/grid/Grid',
    'Ajax',
    'Locale'

], function (QUI, QUIPanel, QUIButtonSeparator, QUIConfirm, Grid, QUIAjax, QUILocale) {
    "use strict";

    const lg = 'quiqqer/info-popup';

    return new Class({

        Extends: QUIPanel,
        Type: 'package/quiqqer/info-popup/bin/controls/Manager',

        Binds: [
            '$onCreate',
            '$onInject',
            '$onResize',
            'loadData',
            'openCreate',
            'openEdit',
            'openDelete',
            '$getProjectData',
            '$refreshButtons'
        ],

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

            this.parent(options);

            this.$Grid = null;
            this.$ProjectSelect = null;

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

        /**
         * event : on create
         */
        $onCreate: function () {
            this.addButton({
                name: 'create',
                text: QUILocale.get(lg, 'panel.button.create'),
                textimage: 'fa fa-plus',
                events: {
                    onClick: this.openCreate
                }
            });

            this.addButton(new QUIButtonSeparator());

            this.addButton({
                name: 'edit',
                text: QUILocale.get(lg, 'panel.button.edit'),
                textimage: 'fa fa-pencil',
                disabled: true,
                events: {
                    onClick: this.openEdit
                }
            });

            this.addButton({
                name: 'delete',
                text: QUILocale.get(lg, 'panel.button.delete'),
                textimage: 'fa fa-trash',
                disabled: true,
                events: {
                    onClick: this.openDelete
                },
                styles: {
                    'float': 'right'
                }
            });

            const Container = new Element('div').inject(this.getContent());

            this.$Grid = new Grid(Container, {
                columnModel: [
                    {
                        header: QUILocale.get(lg, 'grid.active'),
                        dataIndex: 'activeDisplay',
                        dataType: 'node',
                        width: 60
                    },
                    {
                        header: QUILocale.get(lg, 'grid.title'),
                        dataIndex: 'title',
                        dataType: 'string',
                        width: 300
                    },
                    {
                        header: QUILocale.get(lg, 'grid.priority'),
                        dataIndex: 'priority',
                        dataType: 'integer',
                        width: 80
                    },
                    {
                        header: QUILocale.get(lg, 'grid.visibility'),
                        dataIndex: 'visibilityDisplay',
                        dataType: 'string',
                        width: 180
                    },
                    {
                        header: QUILocale.get(lg, 'grid.languages'),
                        dataIndex: 'languagesDisplay',
                        dataType: 'node',
                        width: 140
                    },
                    {
                        header: QUILocale.get(lg, 'grid.validFrom'),
                        dataIndex: 'validFrom',
                        dataType: 'string',
                        width: 150
                    },
                    {
                        header: QUILocale.get(lg, 'grid.validTo'),
                        dataIndex: 'validTo',
                        dataType: 'string',
                        width: 150
                    }
                ],
                pagination: true,
                multipleSelection: false,
                onrefresh: this.loadData
            });

            this.$Grid.addEvents({
                onClick: this.$refreshButtons,
                onDblClick: this.openEdit
            });
        },

        /**
         * event : on inject - add the project select and load
         */
        $onInject: function () {
            const self = this;

            require(['controls/projects/Select'], function (ProjectSelect) {
                self.$ProjectSelect = new ProjectSelect({
                    emptyselect: false,
                    langSelect: false,
                    project: QUIQQER_PROJECT.name,
                    events: {
                        onChange: self.loadData
                    }
                });

                self.addButton(self.$ProjectSelect);
                self.loadData();
            });
        },

        /**
         * event : on resize
         */
        $onResize: function () {
            if (!this.$Grid) {
                return;
            }

            const size = this.getContent().getSize();

            this.$Grid.setHeight(size.y - 40);
            this.$Grid.setWidth(size.x - 40);
        },

        /**
         * Load the grid data for the selected project.
         */
        loadData: function () {
            if (!this.$Grid || !this.$ProjectSelect) {
                return;
            }

            const self = this;
            const projectData = this.$getProjectData();

            if (!projectData) {
                return;
            }

            this.Loader.show();

            QUIAjax.get('package_quiqqer_info-popup_ajax_list', function (result) {
                result.data = result.data.map(function (entry) {
                    entry.activeDisplay = new Element('span', {
                        'class': parseInt(entry.active) ? 'fa fa-check' : 'fa fa-ban'
                    });

                    entry.visibilityDisplay = QUILocale.get(lg, 'visibility.' + entry.visibility);
                    entry.languagesDisplay = self.$renderLanguages(entry.languages);

                    return entry;
                });

                self.$Grid.setData({
                    data: result.data,
                    page: 1,
                    total: result.total
                });
                self.$refreshButtons();
                self.Loader.hide();
            }, {
                'package': 'quiqqer/info-popup',
                project: projectData.name
            });
        },

        /**
         * Render the language targeting of an entry for the grid: "All" when
         * the popup is unrestricted, otherwise a small flag per target code.
         *
         * @param {Array|null} languages
         * @return {HTMLElement}
         */
        $renderLanguages: function (languages) {
            if (!languages || !languages.length) {
                return new Element('span', {
                    text: QUILocale.get(lg, 'grid.languages.all')
                });
            }

            const Container = new Element('span', {
                'class': 'quiqqer-info-popup-grid-languages'
            });

            languages.forEach(function (code) {
                new Element('img', {
                    'class': 'quiqqer-info-popup-grid-languages-flag',
                    src: URL_BIN_DIR + '16x16/flags/' + code + '.png',
                    alt: code,
                    title: code
                }).inject(Container);
            });

            return Container;
        },

        /**
         * Enable / disable the toolbar buttons based on the selection.
         */
        $refreshButtons: function () {
            const selected = this.$Grid.getSelectedData().length;
            const Edit = this.getButtons('edit');
            const Delete = this.getButtons('delete');

            if (selected === 1) {
                Edit.enable();
            } else {
                Edit.disable();
            }

            if (selected >= 1) {
                Delete.enable();
            } else {
                Delete.disable();
            }
        },

        /**
         * Open the edit window in create mode. The entry is only persisted
         * when the user actually saves, so closing without changes creates
         * nothing.
         */
        openCreate: function () {
            if (!this.$getProjectData()) {
                return;
            }

            this.$openEntryWindow(false);
        },

        /**
         * Open the edit window for the selected entry.
         */
        openEdit: function () {
            const selected = this.$Grid.getSelectedData();

            if (!selected.length) {
                return;
            }

            this.$openEntryWindow(selected[0].id);
        },

        /**
         * @param {int} entryId
         */
        $openEntryWindow: function (entryId) {
            const self = this;
            const projectData = this.$getProjectData();

            require(['package/quiqqer/info-popup/bin/controls/EntryWindow'], function (EntryWindow) {
                new EntryWindow({
                    entryId: entryId,
                    projectName: projectData.name,
                    events: {
                        onClose: self.loadData
                    }
                }).open();
            });
        },

        /**
         * Delete the selected entry after confirmation.
         */
        openDelete: function () {
            const selected = this.$Grid.getSelectedData();

            if (!selected.length) {
                return;
            }

            const self = this;
            const entryId = selected[0].id;

            new QUIConfirm({
                icon: 'fa fa-trash',
                title: QUILocale.get(lg, 'window.delete.title'),
                text: QUILocale.get(lg, 'window.delete.title'),
                information: QUILocale.get(lg, 'window.delete.text'),
                maxHeight: 300,
                maxWidth: 450,
                autoclose: false,
                ok_button: {
                    text: QUILocale.get(lg, 'panel.button.delete'),
                    textimage: 'fa fa-trash'
                },
                events: {
                    onSubmit: function (Win) {
                        Win.Loader.show();

                        QUIAjax.post('package_quiqqer_info-popup_ajax_delete', function () {
                            Win.close();
                            self.loadData();
                        }, {
                            'package': 'quiqqer/info-popup',
                            id: entryId
                        });
                    }
                }
            }).open();
        },

        /**
         * Return the selected project data as { name }.
         *
         * @return {Object|null}
         */
        $getProjectData: function () {
            const value = this.$ProjectSelect.getValue();

            if (!value) {
                return null;
            }

            return {
                name: value
            };
        }
    });
});
