/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2023 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('entaxySource', {
        template:
        `
          <div class="route-source-header-container">
            <div>
              <h2>
                Source
              </h2>
              <span class="route-source-error-message" ng-if="$ctrl.xml.trim().length === 0">*{{$ctrl.errorMessage}}</span>
            </div>
            <button type="submit" class="btn btn-primary" ng-click="$ctrl.save()" ng-if="$ctrl.isContentPresent">Save changes</button>
          </div>
          <div ng-if="$ctrl.isContentPresent">
            <div class="xml-route-source-container">
              <entaxy-xml-editor class="xml-editor" source-doc="$ctrl.xml"></entaxy-xml-editor>
            </div>
          </div>
          <div ng-if="$ctrl.isContentPresent === false">There is no viewable content.</div>
        `,
        controller: entaxySourceController
    })
    .name;

    function entaxySourceController(workspace, $location, operationsService, $scope, entaxyService) {
        'ngInject';

        let ctrl = this;
        ctrl.errorMessage = 'Value cannot be empty';

        ctrl.$onInit = function() {

            let mbeanName = workspace.getSelectedMBeanName();

            operationsService
            .executeOperation(mbeanName, { name: 'doGetRouteConfig' }, [])
            .then(result => {
                let info = JSON.parse(result);

                let xml = info.properties.routeContent;
                if (xml) {
                    ctrl.isContentPresent = true;

                    ctrl.objectId = info.objectId;
                    ctrl.factoryId = info.factoryId;
                    ctrl.scope = info.scope;
                    ctrl.systemName = info.properties.systemName;

                    ctrl.xml = atob(xml);
                } else {
                    ctrl.isContentPresent = false;
                }

            }).catch(error => {
                Core.notification('danger', error, 5000);
                Entaxy.log.error(error);
            });
        }

        $scope.$watch('$ctrl.xml', function (newValue, oldValue) {
            if (newValue && oldValue) {
                if (!ctrl.isDirty) {
                    ctrl.isDirty = true;
                }
            }
        });

        setTimeout( function () {
            ctrl.activeTabIndex = entaxyService.getActiveTabIndex();
        })

        $scope.$on("$locationChangeStart", function(event) {
            if (ctrl.isDirty && !confirm('You have unsaved changes. Do you want to leave the page anyway?')) {
                event.preventDefault();
                ctrl.isTreeOrTabSelectionUpdateNeeded = true;
            }
        });

        $scope.$watch('$ctrl.isTreeOrTabSelectionUpdateNeeded', function (newValue) {
            if (newValue) {
                setTimeout(function () {
                    entaxyService.updateTabSelection(ctrl.activeTabIndex);
                });
                Jmx.updateTreeSelectionFromURL($location, $(entaxyTreeElementId));
                ctrl.isTreeOrTabSelectionUpdateNeeded = false;
            }
        });

        ctrl.save = function() {
            entaxyService.requestConfirmationForSavingIfNeededAndProceed(!ctrl.isDirty, save);
        };

        function save() {
            if (ctrl.xml.trim().length !== 0) {
                let factoryFolder = entaxyService.getDomainFolder()
                    .findDescendant(child => child.title === ctrl.factoryId);
                let mbeanName = factoryFolder.objectName
                let properties = { systemName: ctrl.systemName, routeContent: btoa(ctrl.xml) };
                let instructions = {"@LIFECYCLE":["general"]};

                operationsService.executeOperation(mbeanName, { name: 'createObjectByInstructions' }, [ ctrl.objectId, ctrl.scope, instructions, properties ] )
                .then(result => {
                    let tableHtml = Entaxy.createTableFromResponse(result);
                    Entaxy.notification('success', tableHtml, 10000);
                }).catch(error => {
                    Core.notification('danger', error, 5000);
                    Entaxy.log.error(error);
                });

                ctrl.isDirty = false;
            }
        }
    }
    entaxySourceController.$inject = ['workspace', '$location', 'operationsService', '$scope', 'entaxyService'];

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