/*-
 * ~~~~~~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('entaxyUsersTable', {
        bindings: {
            changeSelection: '<',
            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: EntaxyUsersTableController
    })
    .name;

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

        let ctrl = this;
        let selectedMbeanName = workspace.getSelectedMBeanName();

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

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

        ctrl.tableColumns = [
            {
                header: 'Name',
                itemField: 'name',
                htmlTemplate: 'users-table/name-template.html',
                colActionFn: (itemName) => ctrl.changeSelection(itemName)
            }
        ];

        $templateCache.put(
            'users-table/name-template.html',
            '<a href="" ng-click="$ctrl.handleColAction(key, value)">{{value}}</a>'
        );

        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.toLowerCase().match(filter.value.toLowerCase()) !== null;
            }
            return match;
        };

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

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

            let primaryActions = [ { name: 'Add User', actionFn: () => showAddUserModal() } ];

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

            ctrl.tableActionButtons = [
                { name: 'Delete', title: 'Delete User', actionFn: deleteUser }
            ];
        }

        function populateTable() {
            operationsService.executeOperation(selectedMbeanName, { name: 'listUsers' }, [])
            .then(list => {
                ctrl.items = JSON.parse(list);
                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 showAddUserModal() {
            $uibModal.open({
                component: 'entaxyUserManagementModal',
                resolve: {
                    modalTitle: () => 'Add User',
                    formFields: () => [
                        {
                            label: 'Username',
                            name: 'username',
                            type: 'text',
                            required: true,
                            setFocused: true
                        },
                        {
                            label: 'Password',
                            name: 'password',
                            type: 'password',
                            required: true
                        }
                    ]
                },
                backdrop: 'static'
            }).result.then((args) => {
                entaxyService.processUserManagementOperation('addUser', args, populateTable);
            },
            reason => {
                if (reason && reason !== Entaxy.MODAL_CANCEL_REASON.ESCAPE_KEY_PRESS) {
                    Entaxy.notificationError(reason);
                }
            });
        }

        function deleteUser(action, item) {
            ctrl.deletedUsername = item.name;
            entaxyService.processUserManagementOperation('deleteUser', [ item.name ], reload);
        }

        function reload() {
            ctrl.reloadFn(ctrl.deletedUsername);
        }
    }
    EntaxyUsersTableController.$inject = ['workspace', 'operationsService', 'entaxyService', '$uibModal',
        '$templateCache'];

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