/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/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 (shouldShowConnectorsTab()) {
                         tabs.unshift(new Nav.HawtioTab(TAB_CONFIG.connectors.title, TAB_CONFIG.connectors.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 shouldShowConnectorsTab() {
            let mbeanName = workspace.getSelectedMBeanName();
            let parsedMbean = Core.parseMBean(mbeanName);
            return workspace.hasDomainAndProperties(entaxyJmxDomain, {'category': 'profiles'}) &&
                parsedMbean.attributes.profile &&
                !parsedMbean.attributes.section;
        }
//        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/connectors', { template: '<entaxy-connectors></entaxy-connectors>' });
    }
    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'
    },
    connectors: {
        title: 'Connectors',
        route: '/entaxy/connectors'
    }
};
