/*-
 * ~~~~~~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('entaxyAliases', {
        bindings: {
            objectType: '@'
        },
        template:
        `
          <h2>Aliases</h2>

          <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: entaxyAliasesController
    })
    .name;

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

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

        const OBJECT_TYPE = {
            KEYSTORE: 'keystore'
        }

        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' }
        ];

        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 Alias', actionFn: () => ctrl.showAddKeyModal() }
            ];

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

            ctrl.tableActionButtons = [
                { name: 'Remove', title: 'Remove Alias', actionFn: removeAlias }
            ];
        }

        function populateTable() {
            operationsService.executeOperation(selectedMBeanName, { name: 'listAliases' }, [])
            .then(aliases => {
                let items = JSON.parse(aliases);

                ctrl.items = items.map(item => { return { name: item }; });
                ctrl.viewedItems = ctrl.items;

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

        ctrl.showAddKeyModal = function () {
            $uibModal.open({
                component: 'entaxyUserManagementModal',
                resolve: {
                    modalTitle: () => 'Add Alias',
                    formFields: () => [
                        {
                            label: 'Alias',
                            name: 'alias',
                            type: 'text',
                            required: true,
                            setFocused: true
                        },
                        {
                            label: ctrl.objectType === OBJECT_TYPE.KEYSTORE ? 'Key Content' : 'Value',
                            name: ctrl.objectType === OBJECT_TYPE.KEYSTORE ? 'keyContent' : 'value',
                            type: 'textarea',
                            required: true
                        }
                    ]
                },
                backdrop: 'static'
            }).result.then((args) => {
                processOperation(ctrl.objectType === OBJECT_TYPE.KEYSTORE ? 'addKey' : 'writeValue', args);
            },
            reason => {
                if (reason && reason !== Entaxy.MODAL_CANCEL_REASON.ESCAPE_KEY_PRESS) {
                    Entaxy.notificationError(reason);
                }
            });
        }

        function removeAlias(action, item) {
            processOperation(ctrl.objectType === OBJECT_TYPE.KEYSTORE ? 'removeKey' : 'removeValue', [item.name]);
        }

        function processOperation (operationName, properties) {
            operationsService.executeOperation(selectedMBeanName, { name: operationName }, properties)
            .then(result => {
                Entaxy.notificationSuccess(result);
                populateTable();
            })
            .catch(error => {
                Entaxy.notificationError(error);
                Entaxy.log.error(error);
            });
        }

    }
    entaxyAliasesController.$inject = ['workspace', 'operationsService', '$uibModal'];

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