angular.module("app").directive("simpleDataSettings", function ($rootScope, $timeout, BackendService, SQConstants, SQEvents, DataService, AppService, L, ComplexitiesService) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/simpleDataSettings/simpleDataSettings.html",
        scope: {
            instance: '='
        },
        link: function (scope, element, attrs) {

            function loadAvailableData(dataInfo) {
                if (dataInfo && dataInfo.action == SQConstants.getConstants().dataUpdateTypes.rename) {
                    var symbolNames = dataInfo.symbols.split("##");
                    DataService.correctSetupSymbolNames(scope.config, symbolNames[0], symbolNames[1]);
                }

                scope.availableData.length = 0;
                var constants = SQConstants.getConstants();
                if (!constants.data) return;

                for (var i = 0; i < constants.data.length; i++) {
                    var data = constants.data[i];
                    if (data.rows > 0 && data.show) {
                        scope.availableData.push(data);
                    }
                }
            }

            function loadSettings() {
                initialized = false;

                DataService.loadDataConfig();
                updateSettings();

                $timeout(function () { initialized = true; }, 0, false);
            }

            function updateSettings() {
                scope.dateRange = getDateRange();

                var mainSetup = scope.advancedConfig.setups[0];
                if (!mainSetup) return;

                refreshTimeframes(mainSetup.symbol);

                scope.config.engine = mainSetup.engine;
                scope.config.symbol = mainSetup.symbol;
                scope.config.timeframe = mainSetup.timeframe;

                scope.oosRanges = getOOSRanges();

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

            function getDateRange() {
                var mainSetup = scope.advancedConfig.setups[0];
                if (valueFilled(mainSetup)) {
                    return mainSetup.dateFrom + " - " + mainSetup.dateTo;
                }
                return "N/A";
            }

            function getOOSRanges() {
                if (AppService.getTask().type == "Optimize") return "";      //OOS settings are not available in Optimize task

                var text = L.tsq("OOS:") + " ";
                var oosRanges = scope.advancedConfig.oosRanges;

                if (valueFilled(oosRanges) && oosRanges.length) {
                    return text + (oosRanges.length > 1 ? (oosRanges.length + " " + L.tsq("ranges")) : (oosRanges[0].dateFrom + " - " + oosRanges[0].dateTo));
                }
                return text + "N/A";
            }

            function saveSettings() {
                var dataInfo = getItem(scope.availableData, 'symbol', scope.config.symbol);
                if (!dataInfo) {
                    $rootScope.showError(L.tsq("Symbol '%s' doesn't exist", [scope.config.symbol]));
                    return;
                }

                var constants = SQConstants.getConstants();
                var instrumentInfo = getItem(constants.instruments, 'instrument', dataInfo.instrument);
                if (!instrumentInfo) {
                    $rootScope.showError(L.tsq("Instrument '%s' doesn't exist", [instrumentInfo.instrument]));
                    return;
                }

                var setups = scope.advancedConfig.setups;
                setups.length = 1;

                if (setups[0]) {
                    setups[0].engine = scope.config.engine;
                    setups[0].symbol = scope.config.symbol;
                    setups[0].timeframe = scope.config.timeframe;
                }

                DataService.saveSetups(setups);
                SQEvents.notifyListeners(SQEvents.get('MAIN_SETUP_CHANGED'), setups[0]);

                setTimeout(function () { AppService.updateTaskXML(); }, 200);
            }

            function refreshTimeframes(symbol) {
                var dataInfo = getItem(scope.availableData, 'symbol', symbol);
                if (dataInfo) {
                    scope.config.minTimeframe = dataInfo.timeframe;
                    scope.config.timeframe = getNewTimeframe(dataInfo.timeframe, scope.config.timeframe);
                    scope.config.barType = dataInfo.barType;
                }
            }

            function onEvent(event, data) {
                if (event == SQEvents.get('DATA_CHANGED')) {
                    loadAvailableData(data);
                }
                else if (event == SQEvents.get('SETTINGS_TAB_RELOAD')) {
                    if (data == "Data" || data == 'all') {
                        $timeout(loadSettings, 0, false);
                        return;
                    }
                }
                else return;

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

            var destroyConfigWatch = scope.$watch("config", function (newValue, oldValue) {
                if (initialized && !dontSaveChanges) {
                    if (newValue.symbol != oldValue.symbol) {
                        if (newValue == null || newValue == 'null') {
                            scope.config.symbol = '';
                            return;
                        }
                        refreshTimeframes(newValue.symbol);
                        
                        SQEvents.notifyListeners(SQEvents.get('MAIN_SYMBOL_CHANGED'), newValue.symbol);
                    }

                    if (!newValue.symbol) return;        //prevents error messages when deleting used symbol

                    saveSettings();
                }
            }, true);

            var destroyAdvancedConfigWatch = scope.$watch("advancedConfig", function (newValue, oldValue) {
                if (initialized) {
                    dontSaveChanges = true;
                    updateSettings();

                    if (newValue.setups[0].engine != oldValue.setups[0].engine) {
                        ComplexitiesService.setShiftsForCurrentEngine(newValue.setups[0].engine);
                    }

                    $timeout(function () { dontSaveChanges = false; }, 0, false);
                }
            }, true);

            scope.$on("$destroy", function () {
                destroyConfigWatch();
                destroyAdvancedConfigWatch();
                SQEvents.removeListener(listenerId);
            });

            scope.getEngineLabel = function () {
                var engine = getItem(scope.engineTypes, "value", scope.config.engine);
                return engine ? engine.name : '??? '+scope.config.engine;
            }

            var initialized = false;
            var dontSaveChanges = false;

            scope.constants = SQConstants.getConstants();
            scope.engineTypes = angular.copy(scope.constants.engineTypes);
            scope.allTimeframes = angular.copy(scope.constants.timeframes);
            scope.availableData = [];

            scope.advancedConfig = DataService.config;
            scope.config = {};

            loadAvailableData();
            loadSettings();

            var listenerId = "simpleDataSettings";
            SQEvents.addListener(listenerId, [
                SQEvents.get('SETTINGS_TAB_RELOAD'),
                SQEvents.get('DATA_CHANGED')
            ], onEvent);
        }
    };
});