angular.module("app").directive("settingsPanel", function ($timeout, $rootScope, AppService, SQEvents, SettingsService, DataService) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/settingsPanel/settingsPanel.html",
        scope: {
            customGroups: '=',
            instance: '='
        },
        link: function (scope, element, attrs) {
            function loadSettingsGroups() {
                /*
                if(AppService.isTaskManager()) {
                    return;
                }
                */
                reload();
            }

            function onEvent(event, data) {
                if(event == SQEvents.get('TASK_INFO_UPDATE') || event == SQEvents.get('DATA_CHANGED')){
                    $timeout(function(){
                        reload();
                    }, 0, false); //digest needed here
                }
                else if(event == SQEvents.get('LANGUAGE_CHANGED')){
                    scope.$evalAsync();     //force translating 
                }
            }

            function reload(){
                loadToArray(scope.settingsGroups, SettingsService.getTaskInfoPanels(scope.customGroups));
                
                scope.$evalAsync(function(){
                    if(scope.instance.onLoaded) scope.instance.onLoaded();
                });
            }

            scope.showAdvancedSettings = function (event) {
                AppService.switchToPanel('settings');
                event.stopPropagation();
                $timeout(tabsShowHiddenTabs, 0, false);
            }

            if(scope.instance){
                scope.instance.reload = reload;
            }

            scope.settingsGroups = [];
            scope.dataConfig = DataService.config;

            $timeout(loadSettingsGroups, 0, false);       

            var listenerId = "settingsPanel";
            SQEvents.addListener(listenerId, [SQEvents.get('TASK_INFO_UPDATE'), SQEvents.get('DATA_CHANGED'), SQEvents.get('LANGUAGE_CHANGED')], onEvent);

        }
    };
});