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

            function loadSettings() {
                CrossChecksService.list(function () {
                    CrossChecksService.loadConfig();

                    loadCrossChecks();

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

            function loadCrossChecks() {
                scope.categories.length = 0;

                var engineKey = AppService.getCurrentEngineKey();

                for (var i = 0; i < scope.config.crosschecks.length; i++) {
                    var crossCheck = scope.config.crosschecks[i];
                    var service = CrossChecksService.get(crossCheck.name);
                    var catName = getNameByType(crossCheck.type);

                    var category = getItem(scope.categories, 'name', catName);
                    if (!category) {
                        category = {
                            name: catName,
                            position: crossCheck.type,
                            usedCount: 0,
                            crossChecks: []
                        }
                        scope.categories.push(category);
                    }

                    var description = "N/A";

                    if (service && service.getShortInfo) {
                        var settingsElem = CrossChecksService.getSettingsElem(crossCheck.name, "Settings");
                        description = service.getShortInfo(settingsElem);
                    }

                    var crossCheckObj = {
                        use: crossCheck.use,
                        name: crossCheck.name,
                        title: limitString2(crossCheck.title, 32, "."),
                        description: description,
                        forEngine: crossCheck.forEngine
                    };

                    if(!checkForEngine(engineKey, crossCheck.forEngine) || (AppService.getLicense()?.isSpecialTrial && crossCheck.disabledForSpecialTrial)){
                        crossCheckObj.disabled = true;
                        crossCheckObj.use = false;
                    }

                    category.crossChecks.push(crossCheckObj);
                    category.usedCount += crossCheckObj.use ? 1 : 0;
                }
            }

            function updateCategories() {
                for (var i = 0; i < scope.categories.length; i++) {
                    var category = scope.categories[i];
                    category.usedCount = 0;

                    for (var a = 0; a < category.crossChecks.length; a++) {
                        var crossCheck = category.crossChecks[a];
                        var originalCrossCheck = getItem(scope.config.crosschecks, 'name', crossCheck.name);
                        crossCheck.use = originalCrossCheck.use;

                        category.usedCount += crossCheck.use && !scope.config.disabled ? 1 : 0;
                    }

                    category.checked = category.usedCount == category.crossChecks.length;
                    category.halfChecked = category.usedCount != 0 && category.usedCount != category.crossChecks.length;
                }
                
                try { scope.$digest(); } catch(err){}
            }

            function getNameByType(type) {
                switch (type) {
                    case 0: return L.tsq("FAST");
                    case 1: return L.tsq("SLOW");
                    case 2: return L.tsq("VERY SLOW");
                    default: return L.tsq("CUSTOM");
                }
            }

            function getCrossCheckTime(crossCheck) {
                return Math.round(Math.random() * 10000);
            }

            scope.onRecommendedChecked = function () {
                save();
            }

            scope.onCategoryChecked = function (category) {
                disableUpdates = true;

                for (var i = 0; i < category.crossChecks.length; i++) {
                    category.crossChecks[i].use = category.checked;
                    updateOriginalCrossCheck(category.crossChecks[i]);
                }
                save();

                disableUpdates = false;
            }

            scope.onCrossCheckChecked = function (crossCheck) {
                disableUpdates = true;

                updateOriginalCrossCheck(crossCheck);
                save();

                disableUpdates = false;
            }

            scope.onDisableAll = function () {
                save();
            }

            function updateOriginalCrossCheck(crossCheck) {
                var originalCrossCheck = getItem(scope.config.crosschecks, 'name', crossCheck.name);
                if (originalCrossCheck) {
                    originalCrossCheck.use = crossCheck.use;
                }
                else {
                    console.error("Crosscheck '" + crossCheck.name + "' not found");
                }
            }

            function save() {
                CrossChecksService.saveConfig();
                AppService.updateTaskXML();
            }

            $(document).on("click", ".simple-cross-check .learn-more-btn", function (event) {
                AppService.openHelp("cross-checks-automated-strategy-robustness-tests/");
            });

            function onEvent(event, data) {
                if (event == SQEvents.get('SETTINGS_TAB_RELOAD')) {
                    if (data == 'all') {
                        loadSettings();
                    }
                }
                else if (event == SQEvents.get('MAIN_TF_CHANGED') || event == SQEvents.get('REFRESH_CC_TIMES') || event == SQEvents.get('MAIN_SETUP_CHANGED') || event == SQEvents.get('LICENSE_CHANGED')) {
                    loadCrossChecks();
                }
                else return;

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

            var destroyCrossChecksWatch = scope.$watch("config", function (newValue, oldValue) {
                if (loaded && !disableUpdates) {
                    updateCategories();
                }
            }, true);

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

            var loaded = false;
            var disableUpdates = false;

            scope.config = CrossChecksService.config;
            scope.onlyInProTitle = L.tsq("Cross checks are enabled only in Pro version");

            scope.dataConfig = DataService.config;

            scope.categories = [];

            loadSettings();

            var listenerId = "simpleCrossCheck";
            SQEvents.addListener(listenerId, [
                SQEvents.get('SETTINGS_TAB_RELOAD'),
                SQEvents.get('MAIN_TF_CHANGED'),
                SQEvents.get('REFRESH_CC_TIMES'),
                SQEvents.get('MAIN_SETUP_CHANGED'),
                SQEvents.get('LICENSE_CHANGED')
            ], onEvent);

        }
    };
});