/*-
 * ~~~~~~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('entaxyExtendedData', {
        template:
        `
          <div id="entaxy-extended-data" class="entaxy-extended-data" ng-if="$ctrl.messages">
            <uib-accordion>
              <div uib-accordion-group is-open="$ctrl.isOpen">
                <div uib-accordion-heading>
                  <div class="entaxy-extended-data-short-message {{message.type}}" ng-repeat="message in $ctrl.messages">
                    {{message.short}}
                  </div>
                </div>
                <div class="entaxy-extended-data-messages-container">
                  <uib-accordion>
                    <div uib-accordion-group class="entaxy-extended-data-message-container {{message.type}}"
                            ng-class="{'disabled': !message.extraInfo}"
                            is-open="message.open" is-disabled="!message.extraInfo"
                            ng-repeat="message in $ctrl.messages">
                      <div uib-accordion-heading>
                        <span class="pficon"
                            ng-class="{'pficon-edit': !message.type, 'pficon-warning-triangle-o': message.type}"></span>
                        <span class="entaxy-extended-data-message">{{message.full}}</span>
                      </div>
                      <div class="entaxy-extended-data-message-extra-info-container">
                        <pre>{{message.extraInfo}}</pre>
                      </div>
                    </div>
                  </uib-accordion>
                </div>
              </div>
            </uib-accordion>
          </div>
        `,
        controller: entaxyExtendedDataController
    })
    .name;

    function entaxyExtendedDataController(workspace, $scope, $q, entaxyService, entaxyAttributesCacheService) {
        'ngInject';

        let ctrl = this;

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

            $scope.$on('jmxTreeClicked', function () {
                readExtendedData();
            });
        }

        function readExtendedData() {
            ctrl.messages = undefined;
            let selectedMbeanName = workspace.getSelectedMBeanName();

            let attributes;
            if (selectedMbeanName) {
                entaxyAttributesCacheService.setToUpdate(selectedMbeanName);
                attributes = entaxyAttributesCacheService.getAttributes(selectedMbeanName);
            }

            if (attributes && attributes.RuntimeType && attributes.RuntimeType !== Entaxy.RUNTIME_TYPE.ROUTE_CONTAINER) {
                let messages = [];
                let promises = [];

                if (attributes.BundleState) {
                    let status = attributes.BundleState;
                    if (status === 'Failure') {
                        promises.push(entaxyService.getBundleDiag(attributes.BundleId).then(result =>
                            messages.push(getStatusMessage(status, result))));
                    } else {
                        messages.push(getStatusMessage(status));
                    }
                }

                promises.push(entaxyService.readExtendedData(selectedMbeanName)
                .then(result => {
                    let extendedData = JSON.parse(result);

                    if (extendedData.cluster) {
                        messages.push(getClusterMessage(extendedData.cluster));
                    }

                    if (extendedData.applications) {
                        messages.push(getApplicationsMessage(extendedData.applications.application));
                    }
                }));

                $q.all(promises).then(() => {
                    ctrl.messages = messages;
                });
            }
        }

        function getStatusMessage(status, extraInfo) {
            return {
                short: status.toLowerCase(),
                full: 'Status: ' + status,
                extraInfo: extraInfo,
                type: status === 'Failure' ? 'error' : undefined
            };
        }

        function getClusterMessage(cluster) {
            let message = {
                short: cluster.objectClusterState,
                full: 'Cluster: ',
                type: cluster.objectClusterState === Entaxy.OBJECT_CLUSTER_STATE.NON_CLUSTERED ? 'warning' : undefined
            };
            if (cluster.groups && cluster.groups.length > 0) {
                message.full += cluster.groups.join(', ');
            } else {
                message.full += message.short;
            }
            return message;
        }

        function getApplicationsMessage(applications) {
            let message = {
                short: 'managed',
                full: 'Object is installed as a part of the '
            };
            message.full += applications.length > 1 ? 'applications: ' : 'application: ';
            let lastApplicationIndex = applications.length - 1;
            for (let i = 0; i < lastApplicationIndex; i++) {
                message.full += getApplicationFullName(applications[i]) + ', ';
            }
            message.full += getApplicationFullName(applications[lastApplicationIndex]);
            return message;
        }

        function getApplicationFullName(application) {
            return application.name + ':' + application.version + '/' + application.revision;
        }
    }
    entaxyExtendedDataController.$inject = ['workspace', '$scope', '$q', 'entaxyService', 'entaxyAttributesCacheService'];

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