/*-
 * ~~~~~~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.log.debug("loading navigation");
  
    Entaxy._module
    .config(configureRoutes)
    .component('entaxyNavigation', {
        template: `<hawtio-tabs tabs="$ctrl.tabs" on-change="$ctrl.goto(tab)"></hawtio-tabs>`,
        controller: EntaxyNavigationController
    })
    .name;
    Entaxy.log.debug("loaded navigation " + Entaxy.navigationModule);

    function EntaxyNavigationController($scope, $location, workspace, localStorage, jolokia, $rootScope) {
        'ngInject';
        var ctrl = this;
        this.$location = $location;
        entaxyJmxDomain = localStorage['entaxyJmxDomain'] || "ru.entaxy.esb";

        $scope.$on('jmxTreeClicked', function () {
            ctrl.tabs = getTabs();
            var tab = _.find(ctrl.tabs, { path: ctrl.$location.path() });
            if (!tab) {
                tab = ctrl.tabs[0];
            }
            ctrl.$location.path(tab.path);
        });

        EntaxyNavigationController.prototype.$onInit = function () {
            this.tabs = getTabs();
        };

        EntaxyNavigationController.prototype.goto = function (tab) {
            this.$location.path(tab.path);
        };

        function getTabs() {

            var tabs = [];
            var enabledRoutes = Object.keys(TAB_CONFIG)
                .map(function (config) { return TAB_CONFIG[config].route; })
                .filter(function (route) { return _.startsWith(route, '/entaxy'); });
            if (enabledRoutes.length > 0) {
            	tabs.push(new Nav.HawtioTab(TAB_CONFIG.attributes.title, TAB_CONFIG.attributes.route));
            	
            	if (workspace.getSelectedMBeanName()) {
            		if (shouldShowConnectionsTab()) {
            			 tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.connections.title, TAB_CONFIG.connections.route));
            		} else if (shouldShowProfilesTab()) {
                         tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.profiles.title, TAB_CONFIG.profiles.route));
                         // todo smth like goto/$location.search ?
                     } else if (shouldShowConnectorsInProfileTab()) {
                         tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.connectorsInProfile.title, TAB_CONFIG.connectorsInProfile.route));
                         tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.profileProperties.title, TAB_CONFIG.profileProperties.route));
                         tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.profileDiagram.title, TAB_CONFIG.profileDiagram.route));
                     } else if (shouldShowConnectorPropertiesTab()) {
                         tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.connectorProperties.title, TAB_CONFIG.connectorProperties.route));
                     } else if (shouldShowConnectorsTab()) {
                        tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.connectors.title, TAB_CONFIG.connectors.route));
                     } else if (shouldShowSourceTab()) {
                        tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.source.title, TAB_CONFIG.source.route));
                     } else if (shouldShowResourcesTab()) {
                        tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.resources.title, TAB_CONFIG.resources.route));
                     } else if (shouldShowServicesTab()) {
                        tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.services.title, TAB_CONFIG.services.route));
                     } else if (shouldShowServicePropertiesTab()) {
                        tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.serviceProperties.title, TAB_CONFIG.serviceProperties.route));
                     } else {
                    	 let mbeanName = workspace.getSelectedMBeanName();
		                 let parsedMbean = Core.parseMBean(mbeanName);
		                 console.log(parsedMbean);
		                 if (TAB_CONFIG[parsedMbean.attributes.category] &&
		                		 TAB_CONFIG[parsedMbean.attributes.category].check &&
		                		 TAB_CONFIG[parsedMbean.attributes.category].check(workspace)) {
		                	 tabs.unshift(
		                			 new Nav.HawtioTab(TAB_CONFIG[parsedMbean.attributes.category].title,
		                			 TAB_CONFIG[parsedMbean.attributes.category].route));
		                 }
                     }
            		  tabs.push(new Nav.HawtioTab(TAB_CONFIG.operations.title, TAB_CONFIG.operations.route));
            	}
            	
                tabs.push(new Nav.HawtioTab(TAB_CONFIG.chart.title, TAB_CONFIG.chart.route));
//                tabs.push(new Nav.HawtioTab(TAB_CONFIG.test.title, TAB_CONFIG.test.route));
            }
            return tabs;
        }

        function shouldShowConnectionsTab() {
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'connections'}) &&
                workspace.getSelectedMBeanName().endsWith('category=connections');
        }

        function shouldShowProfilesTab() {
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'profiles'}) &&
                workspace.getSelectedMBeanName().endsWith('category=profiles');
        }

        function shouldShowConnectorsInProfileTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'profiles'}) &&
                parsedMbean.attributes.profile &&
                !parsedMbean.attributes.section;
        }

        function shouldShowConnectorPropertiesTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'profiles'}) &&
                workspace.hasDomainAndProperties(entaxyJmxDomain, {'section': 'connectors'}) &&
                parsedMbean.attributes.connector;
        }

        function shouldShowConnectorsTab() {
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'connectors'}) &&
                workspace.getSelectedMBeanName().endsWith('category=connectors');
        }

        function shouldShowSourceTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'profiles'}) &&
                parsedMbean.attributes.profile &&
                parsedMbean.attributes.route;
        }

        function shouldShowResourcesTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'resource'}) &&
                parsedMbean.attributes.provider;
        }

        function shouldShowServicesTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'services'}) &&
                !parsedMbean.attributes.service;
        }

        function shouldShowServicePropertiesTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'services'}) &&
                parsedMbean.attributes.service;
        }

//        global event for entaxy extras
        $rootScope.$emit('entaxyNavigationInited', $scope);
    }
    EntaxyNavigationController.$inject = ['$scope', '$location', 'workspace', 'localStorage', 'jolokia', '$rootScope']

    function configureRoutes($routeProvider) {
       $routeProvider.
        when('/entaxy/attributes', { templateUrl: 'plugins/jmx/html/attributes/attributes.html' }).
        when('/entaxy/operations', { template: '<operations></operations>' }).
        when('/entaxy/charts', { templateUrl: 'plugins/jmx/html/charts.html' }).
        when('/entaxy/test', { template: '<entaxy-test></entaxy-test>' }).
        when('/entaxy/connections', { template: '<entaxy-connections page-title="Connections"></entaxy-connections>' }).
        when('/entaxy/profiles', { template: '<entaxy-profiles page-title="Profiles"></entaxy-profiles>' }).
        when('/entaxy/profile/diagram', { template: '<entaxy-profile-diagram></entaxy-profile-diagram>' }).
        when('/entaxy/profile/properties', { template: '<entaxy-properties item-name="Profile"></entaxy-properties>' }).
        when('/entaxy/profile/connectors', { template: '<entaxy-connectors page-title="Connectors"></entaxy-connectors>' }).
        when('/entaxy/connector/properties', { template: '<entaxy-properties item-name="Connector" use-grand-parent-mbean="true"></entaxy-properties>' }).
        when('/entaxy/connectors', { template: '<entaxy-all-connectors-table></entaxy-all-connectors-table>' }).
        when('/entaxy/route/source', { template: '<entaxy-source></entaxy-source>' }).
        when('/entaxy/resources', { template: '<entaxy-resources></entaxy-resources>' }).
        when('/entaxy/services', { template: '<entaxy-services page-title="Services"></entaxy-services>' }).
        when('/entaxy/service/properties', { template: '<entaxy-properties item-name="Service"></entaxy-properties>' });
    }
    configureRoutes.$inject = ['$routeProvider'];

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

var TAB_CONFIG = {
    attributes: {
        title: 'Attributes',
        route: '/entaxy/attributes'
    },
    operations: {
        title: 'Operations',
        route: '/entaxy/operations'
    },
    chart: {
        title: 'Chart',
        route: '/entaxy/charts'
    },
    test: {
        title: 'Test',
        route: '/entaxy/test'
    },
    connections: {
        title: 'Connections',
        route: '/entaxy/connections'
    },
    profiles: {
        title: 'Profiles',
        route: '/entaxy/profiles'
    },
    profileDiagram: {
        title: 'Profile Diagram',
        route: '/entaxy/profile/diagram'
    },
    profileProperties: {
        title: 'Properties',
        route: '/entaxy/profile/properties'
    },
    connectorsInProfile: {
        title: 'Connectors',
        route: '/entaxy/profile/connectors'
    },
    connectorProperties: {
        title: 'Properties',
        route: '/entaxy/connector/properties'
    },
    connectors: {
        title: 'Connectors',
        route: '/entaxy/connectors'
    },
    source: {
        title: 'Source',
        route: '/entaxy/route/source'
    },
    resources: {
        title: 'Resources',
        route: '/entaxy/resources'
    },
    services: {
        title: 'Services',
        route: '/entaxy/services'
    },
    serviceProperties: {
        title: 'Properties',
        route: '/entaxy/service/properties'
    }
};
