/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-cicd-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 EntaxyCICD;
(function (EntaxyCICD) {
    EntaxyCICD._module.factory('entaxyCICDService', ['$q', 'workspace', 'jolokia', 'jolokiaService', 'operationsService',
        '$uibModal', 'entaxyService',
        function($q, workspace, jolokia, jolokiaService, operationsService, $uibModal, entaxyService) {

            const entaxyCICDJmxDomain = localStorage['entaxyCICDJmxDomain'] || "ru.entaxy.cicd";

            return {
                executeOperation: function (operationName, properties) {
                    return executeOperation(operationName, properties);
                },
                treeUpdated: function () {
                    return treeUpdated();
                },
                setTypesToFilterConfig: function (filterFields) {
                    return setValuesToFilterConfig(filterFields, 'type', 'readApplicationItemTypes');
                },
                setScopesToFilterConfig: function (filterFields) {
                    return setValuesToFilterConfig(filterFields, 'scope', 'readApplicationItemScopes');
                },
                removeItemWithConfirmation: function (itemType, itemName, properties, updateSelectionNode, message) {
                    return removeItemWithConfirmation(itemType, itemName, properties, updateSelectionNode, message);
                }
            };

            function executeOperation(operationName, properties) {
                let mbeanName = getCICDMBeanName();
                let operation = { name : operationName };

                if (mbeanName) {
                    return operationsService.executeOperation(mbeanName, operation, properties);
                } else {
                    return $q.reject("Cannot find mbean for CI/CD");
                }
            }

            function treeUpdated () {
                let rootScope = workspace.$rootScope;
                if (rootScope) {
                    Core.$apply(rootScope);
                    rootScope.$broadcast(Jmx.TreeEvent.Updated, { updateSelectionNode: true });
                }
            }

            function setValuesToFilterConfig(filterFields, fieldId, operationName) {
                let mbean = workspace.findMBeanWithProperties(entaxyCICDJmxDomain, { module: 'applications' });
                let operation = { name: operationName };

                operationsService.executeOperation(mbean.objectName, operation, [])
                .then(result => {
                    let toolbarConfigTypeField = filterFields.find(field => field.id === fieldId);
                    toolbarConfigTypeField.filterValues = JSON.parse(result);
                });
            }

            function removeItemWithConfirmation(itemType, itemName, properties, updateSelectionNode, message) {
                let title = 'Confirm Removing';
                if (!message) {
                    message = 'Do you want to remove the ' + itemType.toLowerCase() + ' ' + itemName + '?';
                }

                entaxyService.openConfirmationWindow(title, message).then(() => {
                    executeOperation('remove' + itemType, properties)
                    .then(result => {
                        Entaxy.notificationSuccess(result);
                        if (updateSelectionNode) {
                            treeUpdated();
                        } else {
                            workspace.jmxTreeUpdated();
                        }
                    })
                    .catch(error => {
                        Entaxy.notificationError(error);
                        EntaxyCICD.log.error(error);
                    });
                });
            }

            function getCICDMBeanName() {
                if (!workspace.hasDomainAndProperties(entaxyCICDJmxDomain)) {
                    return;
                }

                let tree = workspace.tree;
                if (tree) {
                    let domain = tree.get(entaxyCICDJmxDomain);
                    if (domain && domain.children) {
                        for (let i = 0; i < domain.children.length; i++) {
                            if (domain.children[i].folderNames[1] === workspace.selection.folderNames[1]) {
                                return domain.children[i].objectName;
                            }
                        }
                    }
                }
            }
        }
    ])
})(EntaxyCICD || (EntaxyCICD = {}));
