angular.module('app.layout').controller('LayoutCtrl', function ($rootScope, $scope, $timeout, sqPlugin, SQEvents, AppService, SQWebSocketService, SQConstants, SkinService, BackendService, DMDataService) {
    console.log("DataManager's Layout controller initialized");

    $scope.isQuantDataManager = isQuantDataManager();
    $scope.broker = SQConstants.getConstants().broker;
    $scope.isBrazilianEdition = SQConstants.getConstants().isBrazilianEdition;

    $rootScope.brEdition = "";
    if (SQConstants.getConstants().isBrazilianEdition) {
        $rootScope.brEdition = "br-edition";
    }

    $scope.mainTabs = {
        tabs: getPlugins(),
        onSelectTab: onTabChange,
        idPrefix: "dm-tabs",
    }

    function getPlugins() {
        var availablePlugins = sqPlugin.getPlugins("MainTab");
        var plugins = [];

        for (var i = 0; i < availablePlugins.length; i++) {
            var plugin = availablePlugins[i];

            if(isQuantDataManager()) {
                if(plugin.dataItem == 'sessions' || plugin.dataItem == 'custom-da-ta' || plugin.dataItem == 'baskets') continue;
            } else {
                if(plugin.dataItem == 'help') continue;
            }

            plugins.push(plugin);
        }      

        return plugins;
    }

    $scope.selectedMenu = 'add';

    $scope.ribbonActive = "data-sources";

    function onTabChange(tab) {
        //enable/disable actions based on source
        for (var key in $scope.actions) {
            var actions = $scope.actions[key];

            for (var i = 0; i < actions.length; i++) {
                var action = actions[i];

                if (Array.isArray(action)) {
                    for (var j = 0; j < action.length; j++) {
                        action[j].enabled = (action[j].source.indexOf(tab.dataItem) != -1);
                    }
                } else {
                    action.enabled = (action.source.indexOf(tab.dataItem) != -1);
                }
            }
        }

        if(tab.menuActive) {
            $scope.ribbonActive = tab.menuActive;
        }

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

    $scope.onSelectAction = function (action, item) {
        var tabIndex = $scope.mainTabs.getActiveTab().index;

        if (action.onSelect) {
            var data = $scope.mainTabs.tabs[tabIndex].getSelectedRows();

            action.onSelect(data.rows, data.grid, item);
        } else {
            $scope.mainTabs.tabs[tabIndex].callAction(action.key);
        }
    }

    function init() {
         if (SQConstants.getConstants().isBrazilianEdition){
            //find br buttons
            var plugins = sqPlugin.getPlugins("DataManagerActionTools");
            var brBtns = plugins.filter(i=>i.key=='brData' || i.key=='brDataUpdate');
            //add br buttoins to the first position
            console.log('brbuttons', brBtns);
            for(var i = 0;i<brBtns.length;i++){
                $scope.actions.firstTools.push(brBtns[i]);
            }
        }

        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceDukascopy")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceTD")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceFiles")));

        if(isStrategyQuant()) {
            $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceSQEquityData")));
            $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceSQFuturesData")));
        }

        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceDarwinex")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceCrypto")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceYahoo")));

        loadPlugins($scope.actions.exports, angular.copy(sqPlugin.getPlugins("DataManagerActionExport")));

        var actionTools = sqPlugin.getPlugins("DataManagerActionTools");
        actionTools = actionTools.filter(i=>i.key!='brData' && i.key!='brDataUpdate');
        loadPlugins($scope.actions.tools, angular.copy(actionTools));

        loadPlugins($scope.actions.instruments, angular.copy(sqPlugin.getPlugins("DataManagerActionInstrument")));

        loadPlugins($scope.actions.sessions, angular.copy(sqPlugin.getPlugins("DataManagerActionSession")));

        loadPlugins($scope.actions.customData, angular.copy(sqPlugin.getPlugins("DataManagerActionCustomData")));
		
        loadPlugins($scope.actions.baskets, angular.copy(sqPlugin.getPlugins("DataManagerActionBasket")));		
   
        loadPlugins($scope.actions.brokers, angular.copy(sqPlugin.getPlugins("DataManagerActionBroker")));	
    }

    function loadPlugins(array, plugins) {
        array.length = 0;

        for (var i = 0; i < plugins.length; i++) {
            let plugin = plugins[i];

            if(plugin.products && plugin.products.indexOf(window.top.appConfig.product) == -1) {
                continue;
            }

            array.push(plugin);
        }
    }

    $scope.actions = {
        dataSources: [],
        exports: [],
        tools: [],
        firstTools: [],
        instruments: [],
        sessions: [],
        customData: [],
		baskets: [],
        brokers: []
    }

    init();

    /*
    $timeout(function () {
        AppService.notifyAppLoaded();
    }, 1000);*/

    $scope.$on('$viewContentLoaded', function (event) {
        AppService.notifyAppLoaded();
    });

    function onWebSocketData(args) {
        if (args.notification) {
            var data = args.notification;

            if (data.message) {
                $rootScope.showErrorModal(data.title, data.message);

            } else if (data.error) {
                $rootScope.showError(data.error);

            }
        }
        
        if (args.DMConfirmation) {
            var data = args.DMConfirmation;

            $rootScope.showOptionsDialog(data.title, data.message, function (option) {
                BackendService.sendRequest("/data/confirm", {action: option.key});
            }, data.options, true);

            return;
        }

        if (args.DMDataProgresses) {
			var progresses = args.DMDataProgresses;
			for (var i = 0; i < progresses.length; i++) {
				var progress = progresses[i];

				if (progress.key=='TotalProgressSymbol'){
					$scope.progress = progress.pct;
					$scope.progressLabel = progress.message;
					
					if (progress.pct==100){
						$scope.progress = 0;
						$scope.progressLabel = ''
					}
				}			
			}

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

    SQWebSocketService.subscribeGeneral("DataManagerLayoutCtrl", onWebSocketData);

    function performAction(action) {
        console.log("DataManager - Performing action '" + action.name + "'.");

        if (action.name == 'openCDataIndy') {
            $scope.mainTabs.selectTab('custom-da-ta');
        }
    }

    $scope.batchActionPaused = false;

    $scope.batchAction = function(action) {
        if (
            action == "stop" &&
            !confirm(Ltsq("Do you really want to stop all?"))
        ) {
            return;
        }

        $scope.batchActionPaused = action == "pause";

        if (action == "pause") {
            DMDataService.pauseAll();
        } else if (action == "continue") {
            DMDataService.resumeAll();
        } else if (action == "stop") {
            DMDataService.stopAll();
        }
    };

    // QDM help iframe --------------------------------------------------------------------------
    function onEvent(event, data) {
        if (event == SQEvents.get('DATA_CHANGED')) {
            checkData();
        }
    }

    function onSkinChanged() {
        var skin = SkinService.selectedSkin.name;

        if (skin == 'Dark skin') {
            $("#iframe_qdm_no_data").contents().find('body').addClass('dark-skin');
        } else {
            $("#iframe_qdm_no_data").contents().find('body').removeClass('dark-skin');
        }
    }

    function checkData() {
        if (!isQuantDataManager()) {
            return;
        }

        $scope.noData = (SQConstants.getConstants().data && SQConstants.getConstants().data.length == 0);

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

        positionIframeHelp();
    }

    $(window).on("resize", function () {
        positionIframeHelp();
    });

    $("#iframe_qdm_no_data").on("load", function () {
        onSkinChanged();
    });

    function positionIframeHelp() {
        if (!isQuantDataManager()) {
            return;
        }

        var sqGrid = $(".datamanager-main-tabs > .tabs-body > :first-child.active .sq-grid");

        if (sqGrid && sqGrid.length > 0) {
            var sqGridDimensions = sqGrid.offset();
            var sqDMDimensions = $(".sq-app-datamanager").offset();
            var topPos = sqGridDimensions.top + sqDMDimensions.top + 25;
            $("#iframe_qdm_no_data").css("top", topPos + "px").css("left", (11) + "px").css("width", (sqGrid[0].offsetWidth - 2) + "px").css("height", (sqGrid[0].offsetHeight - 26) + "px").addClass("shownReally");
        } else {
            $("#iframe_qdm_no_data").removeClass("shownReally");
        }
    }
    SQEvents.addListener("DataManager", [SQEvents.get('DATA_CHANGED')], onEvent);

    if (isQuantDataManager()) {
        window.parent.addListener("DataManagerSkin", [SQEvents.get("SKIN_CHANGED")], onSkinChanged);
        onSkinChanged();
    } else {
        window.parent.addListener("LayoutCtrl-" + window.appConfig.appCode, [SQEvents.get('APP_SWITCHED'), SQEvents.get("ACTION_REQUEST")], function (event, data) {
            if (event == SQEvents.get('APP_SWITCHED') && data == window.appConfig.product) {
                AppService.onAppSwitched();
            } 
            else if (event == SQEvents.get("ACTION_REQUEST") && data.productCode == window.appConfig.product) {
                performAction(data.action);
            }
        });
    }

    $scope.noData = false;
	$scope.progress=0;
	$scope.progressLabel='';

    checkData();
    //---------------------------------------------------------------------------------------------

    $scope.showDownloadCountConfig = function() {
        $scope.cdnAllowed = AppService.isProVersion();

        showPopup("#downloadCountModal");
    };

    $scope.parallelDownload = { common: 1, cdn: 1, cdnType: "cdn" };

    $scope.parallelDownloadChanged = function() {
        SQConstants.getSettings().cdnPreferred =
            $scope.parallelDownload.cdnType;

        DMDataService.setParallelDownload(
            $scope.parallelDownload.common,
            $scope.parallelDownload.cdn,
            $scope.parallelDownload.cdnType
        );
    };

    DMDataService.getParallelDownload(function(result) {
        $scope.parallelDownload.common = result.parallelDownload;
        $scope.parallelDownload.cdn = result.cdnParallelDownload;
        $scope.parallelDownload.cdnType = result.cdnPreferred;

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

});