/**
 * This tabs panel has only one common tab body. The tabs body content is changed in controller.
 */
angular.module("app").directive("resultsToolbar", function(DatabankService, SQConstants, SQResultsData, SQEvents) {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        templateUrl: "../app/directives/resultsToolbar/toolbar.html",
        scope: {
            onFilterChange: '=',
            displayOnlyData: '=',
            instance: '=?',
            key: '@',
            extSampleType: '@',
        },
        link: function (scope, element, attrs, ctrl, transclude) {
            var eventResultKeyChanged = "ResultKeyChanged";
        
            scope.isMTAnalyzer = isMTAnalyzer();

            scope.onKeySelect = function(){
                callOnFilterChange();
                SQEvents.notifyListeners(eventResultKeyChanged, {key: scope.key, resultKey: scope.resultKey});
            }
            
            scope.onDirectionSelect = function(direction){
                scope.direction = direction;
                callOnFilterChange();
            }

            scope.onSampleTypeChange = function(sampleType){
                scope.sampleType = sampleType;
                callOnFilterChange();
            }
            
            function callOnFilterChange(wfStrategySelected){
                if(scope.onFilterChange){
                    scope.onFilterChange(scope.strategyName, scope.resultKey, scope.direction, scope.isAWCloud ? scope.sampleTypes.full : scope.sampleType, wfStrategySelected);
                }
            }

            function onRefresh(settings){
                var info = SQResultsData.getDataInfo();
                var wfStrategySelected = false;

                scope.strategyName = info.strategyName;

                if(info.dataItems){
                    loadToArray(scope.dataItems, info.dataItems);

                    if(scope.dataItems.includes("Portfolio")) {
                        if(scope.key=='equity-chart' && scope.dataItems.length > 1) {
                            var index = scope.dataItems.indexOf("Portfolio");

                            let isStockpicker =  isBasketAlias(scope.dataItems[1]);
                            if(isStockpicker) {
                                scope.dataItems.splice(index, 1);

                                scope.dataItems.splice(index, 0, equityChart.portfolioOnly);
                            } else {
                                scope.dataItems.splice(index, 0, equityChart.portfolioOnly);
                                scope.dataItems.splice(index+1, 0, equityChart.portfolioPartsOnly);
                            }
                        }
                    }

                    if(settings && scope.dataItems.includes(settings.resultKey)) {
                        scope.resultKey = settings.resultKey;

                    } else if(!scope.resultKey || !scope.dataItems.includes(scope.resultKey)) {
                        scope.resultKey = scope.dataItems.length > 0 ? scope.dataItems[0] : null;

                        if(scope.dataItems.includes("Portfolio") && SQConstants.getConstants().global.defaultResultToDisplay == 'main') {
                            trySetMainResult(info.dataItems);
                        }
                    }   

                    scope.direction = settings ? settings.direction : scope.direction;
                    scope.sampleType = settings ? settings.sampleType : scope.sampleType;

                    wfStrategySelected = trySetWFResult(info.dataItems);

                    //update possible transcluded settings
                    for(attr in settings){
                        if(attr != 'resultKey' && attr != 'direction' && attr != 'sampleType'){
                            scope[attr] = settings[attr];
                        }
                    }
                }
                else {
                    scope.dataItems.length = 0;
                }

                scope.sampleTypeInstance.setResultTypes(null);
                if(info.resultTypes) {
                    scope.sampleTypeInstance.setResultTypes(info.resultTypes);

                    if(!info.resultTypes.includes(scope.sampleType)) {
                        scope.sampleType = scope.sampleTypes.full;
                    }
                }

                try { scope.$digest(); } catch(err) {}
                
                callOnFilterChange(wfStrategySelected);
            }

            function trySetMainResult(dataItems){
                if(!dataItems) return;

                for(var i=0; i<dataItems.length; i++){
                    var resultKey = dataItems[i];
                    if(resultKey.indexOf("Main:") == 0){
                        scope.resultKey = resultKey;
                        break;
                    }
                }
            }

            function trySetWFResult(dataItems){
                if(!dataItems) return false;

                for(var i=0; i<dataItems.length; i++){
                    var resultKey = dataItems[i];
                    if(resultKey.indexOf("WF:") == 0){
                        scope.resultKey = dataItems.indexOf(scope.resultKey) >= 0 ? scope.resultKey : resultKey;
                        //scope.sampleType = scope.sampleTypes.out;
                        return true;
                    }
                }

                return false;
            }

            //- Initialization --------------------------------------------------------------
            
            scope.sampleTypeInstance = {};

            scope.dataItems = [];
            scope.resultKey = null;
            scope.strategyName = null;
            scope.sampleTypes = SQConstants.getConstants().sampleTypes;
            scope.sampleType = scope.sampleTypes.full;
            scope.directions = SQConstants.getConstants().directions;
            scope.direction = scope.directions.both;

            var equityChart = SQConstants.getConstants().equityChart;

            scope.instance = scope.instance || {};
            scope.instance.refresh = onRefresh;

            scope.isAWCloud = SQResultsData.isAlgoWizardCloud();

            //- Event Handlers --------------------------------------------------------------

            function onEvent(event, data) {
                //console.log("result key changed", data, scope.key)

                if(data.key != scope.key && scope.dataItems.includes(data.resultKey)) {
                    scope.resultKey = data.resultKey;

                    callOnFilterChange();
                }
            }

            SQEvents.addListener("resultsToolbar", [eventResultKeyChanged], onEvent);
        }
    };
});