/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
var Entaxy;
(function (Entaxy) {
    Entaxy._module.component('entaxyGroupsTable', {
        bindings: {
            reloadFn: '<'
        },
        template:
        `
          <pf-toolbar class="entaxy-toolbar" config="$ctrl.toolbarConfig"></pf-toolbar>
          <pf-table-view config="$ctrl.tableConfig"
                        columns="$ctrl.tableColumns"
                        action-buttons="$ctrl.tableActionButtons"
                        page-config="$ctrl.pageConfig"
                        items="$ctrl.viewedItems">
          </pf-table-view>
        `,
        controller: EntaxyGroupsTableController
    })
    .name;

    function EntaxyGroupsTableController(workspace, operationsService, entaxyService, $uibModal) {
        'ngInject';

        let ctrl = this;
        let selectedMbeanName = workspace.getSelectedMBeanName();
        let delimeter = ', ';

        ctrl.tableConfig = {
            selectionMatchProp: 'name',
            showCheckboxes: false
        };

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'name',
                        title: 'Group',
                        placeholder: 'Filter by Group...',
                        filterType: 'text'
                    },
                    {
                        id: 'roles',
                        title: 'Roles',
                        placeholder: 'Filter by Roles...',
                        filterType: 'text'
                    }
                ],
                appliedFilters: [],
                onFilterChange: filterChange
            },
            isTableView: true
        };

        ctrl.tableColumns = [
            { header: 'Group', itemField: 'name' },
            { header: 'Roles', itemField: 'roles' }
        ];

        ctrl.pageConfig = Entaxy.getStandardPageConfig();

        function filterChange(filters) {
            ctrl.viewedItems = Entaxy.applyFilters(ctrl.items, filters, matchesFilter);
            ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedItems.length;
        };

        function matchesFilter(item, filter) {
            let match = true;
            if (filter.id === 'name') {
                match = item.name.match(filter.value) !== null;
            } else if (filter.id === 'roles') {
                match = item.roles.match(filter.value) !== null;
            }
            return match;
        };

        ctrl.items = [];
        ctrl.viewedItems = [];

        ctrl.$onInit = function() {
            populateTable();

            let primaryActions = [ { name: 'Create Group', actionFn: () => showCreateGroupModal() } ];

            ctrl.toolbarConfig.actionsConfig = {
                primaryActions: primaryActions
            };

            ctrl.tableActionButtons = [
                { name: 'Add Role', title: 'Add Role', actionFn: addRole },
                { name: 'Delete Role', title: 'Delete Role', actionFn: deleteRole }
            ];
        }

        function populateTable() {
            operationsService.executeOperation(selectedMbeanName, { name: 'listGroups' }, [])
            .then(list => {
                ctrl.items = JSON.parse(list).map(item => {
                    item.roles = item.roles.replaceAll(',', delimeter);
                    return item;
                });
                ctrl.viewedItems = ctrl.items;

                let filters = ctrl.toolbarConfig.filterConfig.appliedFilters;
                if (filters.length > 0) {
                    filterChange(filters);
                } else {
                    ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.items.length;
                }
            })
        }

        function showCreateGroupModal() {
            let resolve = {
                modalTitle: () => 'Create Group',
                formFields: () => [
                    {
                        label: 'Group Name',
                        name: 'group',
                        type: 'text',
                        required: true,
                        setFocused: true
                    }
                ]
            };
            openModalAndProcessResults(resolve, 'createGroup');
        }

        function addRole(action, item) {
            let resolve = {
                modalTitle: () => 'Add Role to Group ' + item.name,
                formFields: () => [
                    {
                        label: 'Group Name',
                        name: 'group',
                        type: 'text',
                        required: true,
                        value: item.name,
                        readOnly: true
                    },
                    {
                        label: 'Role Name',
                        name: 'role',
                        type: 'text',
                        required: true,
                        validation: {
                            checkUniqueness: true,
                            values: item.roles.split(delimeter)
                        },
                        setFocused: true
                    }
                ]
            };
            openModalAndProcessResults(resolve, 'addGroupRole');
        }

        function deleteRole(action, item) {
            let roles = item.roles.split(delimeter);
            roles.shift();
            if (roles.length > 0) {
                let resolve = {
                    modalTitle: () => 'Delete Role from Group ' + item.name,
                    formFields: () => [
                        {
                            name: 'group',
                            type: 'text',
                            required: true,
                            value: item.name,
                            isHidden: true
                        },
                        {
                            label: 'Role Name',
                            name: 'role',
                            type: 'text',
                            required: true,
                            enum: true,
                            values: roles.sort(Entaxy.compare())
                        }
                    ]
                };
                openModalAndProcessResults(resolve, 'deleteGroupRole');
            } else {
                Entaxy.notificationInfo('Group ' + item.name + ' doesn\'t have roles that can be deleted');
            }
        }

        function openModalAndProcessResults(resolve, operationName) {
            $uibModal.open({
                component: 'entaxyUserManagementModal',
                resolve: resolve,
                backdrop: 'static'
            }).result.then((args) => {
                entaxyService.processUserManagementOperation(operationName, args, ctrl.reloadFn);
            }, reason => {
                if (reason && reason !== Entaxy.MODAL_CANCEL_REASON.ESCAPE_KEY_PRESS) {
                    Entaxy.notificationError(reason);
                }
            });
        }
    }
    EntaxyGroupsTableController.$inject = ['workspace', 'operationsService', 'entaxyService', '$uibModal'];

})(Entaxy || (Entaxy = {}));
