package _VisualDVM.TestingSystem.Common;
import Common.CommonConstants;
import Common.Database.SQLITE.SQLiteDatabase;
import Common.Utils.Pair;
import Common.Utils.Utils_;
import _VisualDVM.ComponentsServer.Component.Sapfor.Sapfor;
import _VisualDVM.ComponentsServer.UserAccount.UserAccount;
import _VisualDVM.Constants;
import _VisualDVM.Global;
import _VisualDVM.GlobalData.CompilerEnvironment.Json.EnvironmentJson;
import _VisualDVM.GlobalData.CompilerEnvironment.Json.EnvironmentsJson;
import _VisualDVM.GlobalData.CompilerEnvironment.Json.EnvironmentsSetJson;
import _VisualDVM.GlobalData.CompilerOption.Json.OptionJson;
import _VisualDVM.GlobalData.CompilerOption.Json.OptionsJson;
import _VisualDVM.GlobalData.CompilerOption.Json.OptionsSetJson;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.ServerObjectsCache.VisualCaches;
import _VisualDVM.TestingSystem.Common.Group.Group;
import _VisualDVM.TestingSystem.Common.Group.GroupsDBTable;
import _VisualDVM.TestingSystem.Common.Test.Test;
import _VisualDVM.TestingSystem.Common.Test.TestDBTable;
import _VisualDVM.TestingSystem.Common.TestFile.TestFile;
import _VisualDVM.TestingSystem.Common.TestFile.TestFilesDBTable;
import _VisualDVM.TestingSystem.Common.TestingPackageToKill.TestingPackagesToKillDBTable;
import _VisualDVM.TestingSystem.DVM.DVMCompilationOption.DVMCompilationOption;
import _VisualDVM.TestingSystem.DVM.DVMCompilationOption.DVMCompilationOptionsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMCompilationOptionsSet.DVMCompilationOptionsSet;
import _VisualDVM.TestingSystem.DVM.DVMCompilationOptionsSet.DVMCompilationOptionsSetsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMConfiguration.DVMConfiguration;
import _VisualDVM.TestingSystem.DVM.DVMConfiguration.DVMConfigurationDBTable;
import _VisualDVM.TestingSystem.DVM.DVMConfigurationGroup.DVMConfigurationGroup;
import _VisualDVM.TestingSystem.DVM.DVMConfigurationGroup.DVMConfigurationGroupsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMConfigurationSettings.DVMConfigurationSettings;
import _VisualDVM.TestingSystem.DVM.DVMConfigurationSettings.DVMConfigurationSettingsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMConfigurationTest.DVMConfigurationTest;
import _VisualDVM.TestingSystem.DVM.DVMConfigurationTest.DVMConfigurationTestsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMEnvironment.DVMEnvironment;
import _VisualDVM.TestingSystem.DVM.DVMEnvironment.DVMEnvironmentsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMEnvironmentsSet.DVMEnvironmentsSet;
import _VisualDVM.TestingSystem.DVM.DVMEnvironmentsSet.DVMEnvironmentsSetsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMPackage.DVMPackage;
import _VisualDVM.TestingSystem.DVM.DVMPackage.DVMPackageDBTable;
import _VisualDVM.TestingSystem.DVM.DVMPackageConfiguration.DVMPackageConfiguration;
import _VisualDVM.TestingSystem.DVM.DVMPackageConfiguration.DVMPackageConfigurationsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMSettings.DVMSettings;
import _VisualDVM.TestingSystem.DVM.DVMSettings.DVMSettingsDBTable;
import _VisualDVM.TestingSystem.DVM.DVMTasks.DVMRunTasksSet;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfiguration.SapforConfiguration;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfiguration.SapforConfigurationDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfigurationGroup.SapforConfigurationGroup;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfigurationGroup.SapforConfigurationGroupsDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfigurationSettings.SapforConfigurationSettings;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfigurationSettings.SapforConfigurationSettingsDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfigurationTest.SapforConfigurationTest;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfigurationTest.SapforConfigurationTestsDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackage.SapforPackage;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackage.SapforPackageDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackageConfiguration.SapforPackageConfiguration;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackageConfiguration.SapforPackageConfigurationsDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforSettings.SapforSettings;
import _VisualDVM.TestingSystem.SAPFOR.SapforSettings.SapforSettingsDBTable;
import _VisualDVM.TestingSystem.SAPFOR.SapforSettingsCommand.SapforSettingsCommand;
import _VisualDVM.TestingSystem.SAPFOR.SapforSettingsCommand.SapforSettingsCommandsDBTable;
import _VisualDVM.TestingSystem.SAPFOR.ServerSapfor.ServerSapfor;
import _VisualDVM.TestingSystem.SAPFOR.ServerSapfor.ServerSapforState;
import _VisualDVM.TestingSystem.SAPFOR.ServerSapfor.ServerSapforsDBTable;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Vector;
public class TestsDatabase extends SQLiteDatabase {
    public GroupsDBTable groups;
    //--
    public TestDBTable tests;
    public TestFilesDBTable testsFiles;
    //---
    public DVMSettingsDBTable dvmSettings;
    public DVMCompilationOptionsSetsDBTable dvmCompilationOptionsSets;
    public DVMCompilationOptionsDBTable dvmCompilationOptions;
    public DVMEnvironmentsSetsDBTable dvmEnvironmentsSets;
    public DVMEnvironmentsDBTable dvmEnvironments;
    public DVMConfigurationDBTable dvmConfigurations;
    public DVMConfigurationGroupsDBTable dvmConfigurationGroups;
    public DVMConfigurationTestsDBTable dvmConfigurationTests;
    public DVMConfigurationSettingsDBTable dvmConfigurationSettings;
    public DVMPackageDBTable dvmPackages;
    public DVMPackageConfigurationsDBTable dvmPackageConfigurations;
    public DVMRunTasksSet dvmRunTasks = new DVMRunTasksSet();
    //--
    public ServerSapforsDBTable serverSapfors;
    public SapforSettingsDBTable sapforSettings;
    public SapforSettingsCommandsDBTable sapforSettingsCommands;
    public SapforConfigurationDBTable sapforConfigurations;
    public SapforConfigurationGroupsDBTable sapforConfigurationGroups;
    public SapforConfigurationTestsDBTable sapforConfigurationTests;
    public SapforConfigurationSettingsDBTable sapforConfigurationSettings;
    public SapforPackageDBTable sapforPackages;
    public SapforPackageConfigurationsDBTable sapforPackageConfigurations;
    //--
    public TestingPackagesToKillDBTable testingPackagesToKill;
    //--
    public TestsDatabase() {
        super(Paths.get(System.getProperty("user.dir"), "Data", Constants.tests_db_name + ".sqlite").toFile());
    }
    public static String printOptionsLine(Vector<DVMCompilationOption> options) {
        Vector<String> res = new Vector<>();
        for (DVMCompilationOption option : options)
            res.add(option.print());
        return String.join(" ", res);
    }
    public static String printEnvironmentsLine(Vector<DVMEnvironment> environments) {
        Vector<String> res = new Vector<>();
        for (DVMEnvironment environment : environments)
            res.add(environment.print());
        return String.join(" ", res);
    }
    @Override
    protected void initAllTables() throws Exception {
        addTable(groups = new GroupsDBTable());
        addTable(tests = new TestDBTable());
        addTable(testsFiles = new TestFilesDBTable());
        //--
        addTable(dvmSettings = new DVMSettingsDBTable());
        //--
        addTable(dvmCompilationOptionsSets = new DVMCompilationOptionsSetsDBTable());
        addTable(dvmCompilationOptions = new DVMCompilationOptionsDBTable());
        addTable(dvmEnvironmentsSets = new DVMEnvironmentsSetsDBTable());
        addTable(dvmEnvironments = new DVMEnvironmentsDBTable());
        //---
        addTable(dvmConfigurations = new DVMConfigurationDBTable());
        addTable(dvmConfigurationGroups = new DVMConfigurationGroupsDBTable());
        addTable(dvmConfigurationTests = new DVMConfigurationTestsDBTable());
        addTable(dvmConfigurationSettings = new DVMConfigurationSettingsDBTable());
        addTable(dvmPackages = new DVMPackageDBTable());
        addTable(dvmPackageConfigurations = new DVMPackageConfigurationsDBTable());
        //-
        addTable(serverSapfors = new ServerSapforsDBTable());
        addTable(sapforSettings = new SapforSettingsDBTable());
        addTable(sapforSettingsCommands = new SapforSettingsCommandsDBTable());
        addTable(sapforConfigurations = new SapforConfigurationDBTable());
        addTable(sapforConfigurationGroups = new SapforConfigurationGroupsDBTable());
        addTable(sapforConfigurationTests = new SapforConfigurationTestsDBTable());
        addTable(sapforConfigurationSettings = new SapforConfigurationSettingsDBTable());
        addTable(sapforPackages = new SapforPackageDBTable());
        addTable(sapforPackageConfigurations = new SapforPackageConfigurationsDBTable());
        //--
        addTable(testingPackagesToKill = new TestingPackagesToKillDBTable());
    }
    @Override
    public PassCode getSynchronizePassCode() {
        return PassCode.SynchronizeTests;
    }
    public Vector<SapforPackage> getFirstActiveSapforPackagesCopies() {
        Vector<SapforPackage> res = new Vector<>();
        Vector<SapforPackage> packages = new Vector<>();
        SapforPackage activePackage = null;
        //1. получить активные пакеты.
        for (SapforPackage p : sapforPackages.Data.values()) {
            switch (p.state) {
                case Done:
                case Aborted:
                case Draft:
                case ConnectionError:
                case DoneWithErrors:
                    break;
                default:
                    packages.add(p);
                    break;
            }
        }
        //2. отсортировать по приоритету.
        packages.sort(new Comparator<SapforPackage>() {
            @Override
            public int compare(SapforPackage o1, SapforPackage o2) {
                return Integer.compare(o1.state.ordinal(), o2.state.ordinal());
            }
        });
        if (!packages.isEmpty()) {
            activePackage = packages.lastElement();
            if (activePackage.state.equals(TasksPackageState.Queued)) {
                activePackage.state = TasksPackageState.TestsSynchronize;
                try {
                    Update(activePackage);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            res.add(new SapforPackage(activePackage));
            ; //копия чтобы не было конфликта доступа с нитью планировщика.
        }
        return res;
    }
    public Vector<DVMPackage> getFirstActiveDVMPackagesCopies() {
        Vector<DVMPackage> res = new Vector<>();
        //--
        LinkedHashMap<String, Vector<DVMPackage>> packagesByMachines = new LinkedHashMap<>();
        //----
        //1. Получить список активных пакетов по машинам.
        for (DVMPackage dvmPackage : dvmPackages.Data.values()) {
            switch (dvmPackage.state) {
                case Done:
                case DoneWithErrors:
                case Aborted:
                case Draft:
                case ConnectionError:
                    break;
                default:
                    //активен.
                    Vector<DVMPackage> packages = null;
                    //--
                    if (packagesByMachines.containsKey(dvmPackage.machine_address)) {
                        packages = packagesByMachines.get(dvmPackage.machine_address);
                    } else {
                        packages = new Vector<>();
                        packagesByMachines.put(dvmPackage.machine_address, packages);
                    }
                    packages.add(dvmPackage);
                    break;
            }
        }
        //2. Выбрать для каждой машины наиболее приоритетный пакет.
        for (String machine : packagesByMachines.keySet()) {
            Vector<DVMPackage> packages = packagesByMachines.get(machine);
            if (!packages.isEmpty()) {
                packages.sort(new Comparator<DVMPackage>() {
                    @Override
                    public int compare(DVMPackage o1, DVMPackage o2) {
                        return Integer.compare(o1.state.ordinal(), o2.state.ordinal());
                    }
                });
                //-
                DVMPackage activePackage = packages.lastElement();
                if (activePackage.state.equals(TasksPackageState.Queued)) {
                    activePackage.state = TasksPackageState.TestsSynchronize;
                    try {
                        Update(activePackage);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                res.add(new DVMPackage(activePackage)); //копия чтобы не было конфликта доступа с нитью планировщика.
            }
        }
        return res;
    }
    //--
    public void DetectTestMinMaxDim(ServerSapfor serverSapfor, Group group, Test test) throws Exception {
        switch (group.language) {
            case fortran:
                if (serverSapfor != null) {
                    Sapfor.getTestMinMaxDim_F(new File(serverSapfor.call_command), test);
                    Update(test);
                }
                break;
            case c:
                Sapfor.getTestMinMaxDime_C(test);
                Update(test);
                break;
        }
    }
    public void importTestFile(Test test, File file) throws Exception {
        File testDirectory = new File(Global.TestsDirectory, String.valueOf(test.id));
        Utils_.CheckAndCleanDirectory(testDirectory);
        File dst = Paths.get(testDirectory.getAbsolutePath(), file.getName()).toFile();
        FileUtils.copyFile(file, dst);
    }
    public void CreateTestFromSingleFile(UserAccount account, ServerSapfor sapfor, Group group, File file, String testDescription) throws Exception {
        Test test = new Test();
        test.description = testDescription;
        test.sender_name = account.name;
        test.sender_address = account.email;
        test.group_id = group.id;
        Insert(test);
        //->>
        importTestFile(test, file);
        TestFile testFile = new TestFile(test, file);
        Insert(testFile);
        //--
        DetectTestMinMaxDim(sapfor, group, test);
    }
    public void RefreshGroup(UserAccount account, ServerSapfor sapfor, Pair<Group, Vector<File>> groupData) throws Exception {
        Group group = groupData.getKey();
        Vector<File> files = groupData.getValue();
        //--
        Group oldGroup = groups.getGroupByDescription(group.language, group.description);
        if (oldGroup == null) {
            Insert(group);
            for (File file : files) {
                String testDescription = Utils_.getNameWithoutExtension(file.getName()) + "_" + group.language.getDVMCompile();
                CreateTestFromSingleFile(account, sapfor, group, file, testDescription);
            }
        } else {
            for (File file : files) {
                String testDescription = Utils_.getNameWithoutExtension(file.getName()) + "_" + group.language.getDVMCompile();
                Test oldTest = tests.getStandardTestByDescription(oldGroup.id, testDescription);
                if (oldTest == null) {
                    CreateTestFromSingleFile(account, sapfor, oldGroup, file, testDescription);
                } else {
                    importTestFile(oldTest, file);
                }
            }
        }
    }
    public Vector<DVMPackage> getFirstActiveDVMPackageCopyForMachineURL(String arg) {
        Vector<DVMPackage> res = new Vector<>();
        Vector<DVMPackage> machinePackages = new Vector<>();
        //--
        //1. Получить список активных пакетов для машины.
        for (DVMPackage dvmPackage : dvmPackages.Data.values()) {
            switch (dvmPackage.state) {
                case Done:
                case DoneWithErrors:
                case Aborted:
                case Draft:
                case ConnectionError:
                    break;
                default:
                    if (dvmPackage.getMachineURL().equals(arg))
                        machinePackages.add(dvmPackage);
                    break;
            }
        }
        if (!machinePackages.isEmpty()) {
            machinePackages.sort(new Comparator<DVMPackage>() {
                @Override
                public int compare(DVMPackage o1, DVMPackage o2) {
                    return Integer.compare(o1.state.ordinal(), o2.state.ordinal());
                }
            });
            //-
            DVMPackage activePackage = machinePackages.lastElement();
            if (activePackage.state.equals(TasksPackageState.Queued)) {
                activePackage.state = TasksPackageState.TestsSynchronize;
                try {
                    Update(activePackage);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            res.add(new DVMPackage(activePackage));
        }
        return res;
    }
    public ServerSapfor getSapforCopyForCompilation() {
        for (ServerSapfor serverSapfor : serverSapfors.Data.values()) {
            if (serverSapfor.state.equals(ServerSapforState.Queued)) {
                return new ServerSapfor(serverSapfor);
            }
        }
        return null;
    }
    public ServerSapfor getSapforForVersion(String version_in) {
        for (ServerSapfor serverSapfor : serverSapfors.Data.values()) {
            if (serverSapfor.version.equals(version_in))
                return serverSapfor;
        }
        return null;
    }
    public Integer getInstalledSapforMaxVersion() {
        int max_version = CommonConstants.Nan;
        for (ServerSapfor sapfor : serverSapfors.Data.values()) {
            if (sapfor.state.equals(ServerSapforState.Done)) {
                int version = CommonConstants.Nan;
                try {
                    version = Integer.parseInt(sapfor.version);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (version > max_version) max_version = version;
            }
        }
        return max_version;
    }
    public boolean hasActiveSapfors() {
        for (ServerSapfor serverSapfor : serverSapfors.Data.values()) {
            if (serverSapfor.state.isActive())
                return true;
        }
        return false;
    }
    public void UnselectAllGTC() {
        groups.getUI().SelectAll(false);
        tests.getUI().SelectAll(false);
        dvmConfigurations.getUI().SelectAll(false);
    }
    //todo возможно рассмотреть вариант с синхроннизацией тестов для пакетов через команду серверу а не в нити
    //во избежание конфликта доступа,или удалением тестов во время копирования(?)
    @Override
    public void DropUI() {
        super.DropUI();
        dvmConfigurations.ClearUI();
        groups.ClearUI();
        sapforConfigurations.ClearUI();
        serverSapfors.ClearUI();
        dvmPackages.ClearUI();
        sapforPackages.ClearUI();
        sapforSettings.ClearUI();
        dvmSettings.ClearUI();
    }
    @Override
    public void ResetUI() {
        VisualCaches.ClearDataForClass(DVMConfiguration.class);
        VisualCaches.ClearDataForClass(SapforConfiguration.class);
        VisualCaches.ClearDataForClass(DVMPackage.class);
        VisualCaches.ClearDataForClass(SapforPackage.class);
        //server.db.machines
        dvmConfigurations.ShowUI();
        groups.ShowUI();
        sapforConfigurations.ShowUI();
        serverSapfors.ShowUI();
        dvmPackages.ShowUI();
        sapforPackages.ShowUI();
        sapforSettings.ShowUI();
        dvmSettings.ShowUI();
        super.ResetUI();
    }
    public void saveTestFiles(Test test) throws Exception {
        for (TestFile file : test.files) {
            file.test_id = test.id;
            Insert(file);
        }
        test.files = null;
    }
    public void DeleteTestFiles(Test test) throws Exception {
        Vector<TestFile> files = getVectorByFK(test, TestFile.class);
        for (TestFile file : files)
            Delete(file);
    }
    public void saveDVMPackageConfigurations(DVMPackage dvmPackage) throws Exception {
        for (DVMPackageConfiguration packageConfiguration : dvmPackage.configurations) {
            packageConfiguration.dvmpackage_id = dvmPackage.id;
            Insert(packageConfiguration);
        }
        dvmPackage.configurations = null;
    }
    public void saveSapforPackageConfigurations(SapforPackage dvmPackage) throws Exception {
        for (SapforPackageConfiguration packageConfiguration : dvmPackage.configurations) {
            packageConfiguration.sapforpackage_id = dvmPackage.id;
            Insert(packageConfiguration);
        }
        dvmPackage.configurations = null;
    }
    public Vector<Integer> getDVMConfigurationGroupsIds(DVMConfiguration configuration) {
        Vector<Integer> res = new Vector<>();
        for (DVMConfigurationGroup dvmConfigurationGroup : dvmConfigurationGroups.Data.values()) {
            if (dvmConfigurationGroup.dvmconfiguration_id == configuration.id)
                res.add(dvmConfigurationGroup.group_id);
        }
        return res;
    }
    public Vector<Integer> getDVMConfigurationTestsIds(DVMConfiguration configuration) {
        Vector<Integer> res = new Vector<>();
        if (configuration.groupsOnly == 0) {
            for (DVMConfigurationTest dvmConfigurationTest : dvmConfigurationTests.Data.values()) {
                if (dvmConfigurationTest.dvmconfiguration_id == configuration.id)
                    res.add(dvmConfigurationTest.test_id);
            }
        } else {
            Vector<Integer> groups_ids = getDVMConfigurationGroupsIds(configuration);
            for (int groud_id : groups_ids)
                res.addAll(getFKi(groud_id, Group.class, Test.class));
        }
        return res;
    }
    public Vector<Integer> getDVMConfigurationSettingsIds(DVMConfiguration configuration) {
        Vector<Integer> res = new Vector<>();
        for (DVMConfigurationSettings dvmConfigurationSettings : dvmConfigurationSettings.Data.values()) {
            if (dvmConfigurationSettings.dvmconfiguration_id == configuration.id)
                res.add(dvmConfigurationSettings.dvmsettings_id);
        }
        return res;
    }
    //--
    public Vector<Integer> getSapforConfigurationGroupsIds(SapforConfiguration configuration) {
        Vector<Integer> res = new Vector<>();
        for (SapforConfigurationGroup sapforConfigurationGroup : sapforConfigurationGroups.Data.values()) {
            if (sapforConfigurationGroup.sapforconfiguration_id == configuration.id)
                res.add(sapforConfigurationGroup.group_id);
        }
        return res;
    }
    public Vector<Integer> getSapforConfigurationTestsIds(SapforConfiguration configuration) {
        Vector<Integer> res = new Vector<>();
        if (configuration.groupsOnly == 0) {
            for (SapforConfigurationTest sapforConfigurationTest : sapforConfigurationTests.Data.values()) {
                if (sapforConfigurationTest.sapforconfiguration_id == configuration.id)
                    res.add(sapforConfigurationTest.test_id);
            }
        } else {
            Vector<Integer> groups_ids = getSapforConfigurationGroupsIds(configuration);
            for (int groud_id : groups_ids)
                res.addAll(getFKi(groud_id, Group.class, Test.class));
        }
        return res;
    }
    public Vector<Integer> getSapforConfigurationSettingsIds(SapforConfiguration configuration) {
        Vector<Integer> res = new Vector<>();
        for (SapforConfigurationSettings sapforConfigurationSettings : sapforConfigurationSettings.Data.values()) {
            if (sapforConfigurationSettings.sapforconfiguration_id == configuration.id)
                res.add(sapforConfigurationSettings.sapforsettings_id);
        }
        return res;
    }
    //--
    public LinkedHashMap<Integer, Vector<Integer>> getDVMConfigurationGroupsTestsIds(DVMConfiguration configuration) {
        LinkedHashMap<Integer, Vector<Integer>> res = new LinkedHashMap<>();
        Vector<Integer> all_tests_ids = getDVMConfigurationTestsIds(configuration);
        for (int group_id : getDVMConfigurationGroupsIds(configuration)) {
            Vector<Integer> test_ids = new Vector<>();
            for (int test_id : all_tests_ids) {
                if (tests.get(test_id).group_id == group_id)
                    test_ids.add(test_id);
            }
            res.put(group_id, test_ids);
        }
        return res;
    }
    public LinkedHashMap<Integer, Vector<Integer>> getSapforConfigurationGroupsTestsIds(SapforConfiguration configuration) {
        LinkedHashMap<Integer, Vector<Integer>> res = new LinkedHashMap<>();
        Vector<Integer> all_tests_ids = getSapforConfigurationTestsIds(configuration);
        for (int group_id : getSapforConfigurationGroupsIds(configuration)) {
            Vector<Integer> test_ids = new Vector<>();
            for (int test_id : all_tests_ids) {
                if (tests.get(test_id).group_id == group_id)
                    test_ids.add(test_id);
            }
            res.put(group_id, test_ids);
        }
        return res;
    }
    //--
    public Vector<Integer> getDVMPackageConfigurationsIds(DVMPackage dvmPackage) {
        Vector<Integer> res = new Vector<>();
        for (DVMPackageConfiguration dvmPackageConfiguration : dvmPackageConfigurations.Data.values()) {
            if (dvmPackageConfiguration.dvmpackage_id == dvmPackage.id)
                res.add(dvmPackageConfiguration.dvmconfiguration_id);
        }
        return res;
    }
    public Vector<Integer> getSapforPackageConfigurationsIds(SapforPackage sapforPackage) {
        Vector<Integer> res = new Vector<>();
        for (SapforPackageConfiguration sapforPackageConfiguration : sapforPackageConfigurations.Data.values()) {
            if (sapforPackageConfiguration.sapforpackage_id == sapforPackage.id)
                res.add(sapforPackageConfiguration.sapforconfiguration_id);
        }
        return res;
    }
    //--
    public OptionsSetJson convertOptionsToJson(DVMSettings dvmSettings_in) {
        OptionsSetJson res = new OptionsSetJson();
        if (dvmSettings_in.id != CommonConstants.Nan) {
            Vector<DVMCompilationOptionsSet> optionsSets = getVectorByFK(dvmSettings_in, DVMCompilationOptionsSet.class);
            for (DVMCompilationOptionsSet optionsSet : optionsSets) {
                Vector<DVMCompilationOption> options = getVectorByFK(optionsSet, DVMCompilationOption.class);
                OptionsJson optionsJson = new OptionsJson();
                for (DVMCompilationOption option : options) {
                    optionsJson.values.add(new OptionJson(option.name, option.value));
                }
                res.values.add(optionsJson);
            }
        }
        return res;
    }
    public EnvironmentsSetJson convertEnvironmentsToJson(DVMSettings dvmSettings_in) {
        EnvironmentsSetJson res = new EnvironmentsSetJson();
        if (dvmSettings_in.id != CommonConstants.Nan) {
            Vector<DVMEnvironmentsSet> environmentsSets = getVectorByFK(dvmSettings_in, DVMEnvironmentsSet.class);
            for (DVMEnvironmentsSet environmentsSet : environmentsSets) {
                Vector<DVMEnvironment> environments = getVectorByFK(environmentsSet, DVMEnvironment.class);
                EnvironmentsJson environmentsJson = new EnvironmentsJson();
                for (DVMEnvironment option : environments) {
                    environmentsJson.values.add(new EnvironmentJson(option.name, option.value));
                }
                res.values.add(environmentsJson);
            }
        }
        return res;
    }
    public void DeleteDVMSettingsOptions(DVMSettings dvmSettings) throws Exception {
        Vector<DVMCompilationOptionsSet> optionsSets = getVectorByFK(dvmSettings, DVMCompilationOptionsSet.class);
        for (DVMCompilationOptionsSet optionsSet : optionsSets) {
            DeleteDependencies(optionsSet);
            Delete(optionsSet);
        }
    }
    public void InsertDVMSettingsOptions(DVMSettings dvmSettings) throws Exception {
        OptionsSetJson optionsSetJson = Utils_.gson.fromJson(dvmSettings.packedCompilationOptionsJson, OptionsSetJson.class);
        for (OptionsJson optionsJson : optionsSetJson.values) {
            DVMCompilationOptionsSet optionsSet = new DVMCompilationOptionsSet(dvmSettings);
            Insert(optionsSet);
            for (OptionJson optionJson : optionsJson.values) {
                DVMCompilationOption option = new DVMCompilationOption();
                option.dvmcompilationoptionsset_id = optionsSet.id;
                option.name = optionJson.name;
                option.value = optionJson.value;
                Insert(option);
            }
        }
    }
    public void DeleteDVMSettingsEnvironments(DVMSettings dvmSettings) throws Exception {
        Vector<DVMEnvironmentsSet> environmentsSets = getVectorByFK(dvmSettings, DVMEnvironmentsSet.class);
        for (DVMEnvironmentsSet environmentsSet : environmentsSets) {
            DeleteDependencies(environmentsSet);
            Delete(environmentsSet);
        }
    }
    public void InsertDVMSettingsEnvironments(DVMSettings dvmSettings) throws Exception {
        EnvironmentsSetJson environmentsSetJson = Utils_.gson.fromJson(dvmSettings.packedRunEnvironmentValuesJson, EnvironmentsSetJson.class);
        for (EnvironmentsJson environmentsJson : environmentsSetJson.values) {
            DVMEnvironmentsSet environmentsSet = new DVMEnvironmentsSet(dvmSettings);
            Insert(environmentsSet);
            for (EnvironmentJson environmentJson : environmentsJson.values) {
                DVMEnvironment environment = new DVMEnvironment();
                environment.dvmenvironmentsset_id = environmentsSet.id;
                environment.name = environmentJson.name;
                environment.value = environmentJson.value;
                Insert(environment);
            }
        }
    }
    //--
    public void CloneDVMSettings(DVMSettings dvmSettings_src, DVMSettings dvmSettings_dst) throws Exception {
        //--
        Vector<DVMCompilationOptionsSet> optionsSets_src = getVectorByFK(dvmSettings_src, DVMCompilationOptionsSet.class);
        for (DVMCompilationOptionsSet optionsSet_src : optionsSets_src) {
            DVMCompilationOptionsSet optionsSet_dst = new DVMCompilationOptionsSet(dvmSettings_dst);
            Insert(optionsSet_dst);
            //--
            Vector<DVMCompilationOption> options_src = getVectorByFK(optionsSet_src, DVMCompilationOption.class);
            Vector<DVMCompilationOption> options_dst = new Vector<>();
            //--
            for (DVMCompilationOption option_src : options_src) {
                DVMCompilationOption option_dst = new DVMCompilationOption();
                option_dst.dvmcompilationoptionsset_id = optionsSet_dst.id;
                option_dst.name = option_src.name;
                option_dst.value = option_src.value;
                Insert(option_dst);
            }
        }
        //--
        Vector<DVMEnvironmentsSet> environmentsSets_src = getVectorByFK(dvmSettings_src, DVMEnvironmentsSet.class);
        for (DVMEnvironmentsSet environmentsSet_src : environmentsSets_src) {
            DVMEnvironmentsSet environmentsSet_dst = new DVMEnvironmentsSet(dvmSettings_dst);
            Insert(environmentsSet_dst);
            //--
            Vector<DVMEnvironment> environments_src = getVectorByFK(environmentsSet_src, DVMEnvironment.class);
            Vector<DVMEnvironment> environments_dst = new Vector<>();
            //--
            for (DVMEnvironment environment_src : environments_src) {
                DVMEnvironment environment_dst = new DVMEnvironment();
                environment_dst.dvmenvironmentsset_id = environmentsSet_dst.id;
                environment_dst.name = environment_src.name;
                environment_dst.value = environment_src.value;
                Insert(environment_dst);
            }
        }
    }
    public void CloneSapforSettings(SapforSettings src, SapforSettings dst) throws Exception {
        for (SapforSettingsCommand src_command : getVectorByFK(src, SapforSettingsCommand.class)) {
            SapforSettingsCommand dst_command = new SapforSettingsCommand();
            dst_command.sapforsettings_id = dst.id;
            dst_command.passCode = src_command.passCode;
            Insert(dst_command);
        }
    }
    //--
    public Vector<Pair<String, String>> getTasksParameters(DVMSettings dvmSettings_in) {
        //уравниваем количество наборов опций и окружений и сопоставляем 1 к 1
        Vector<Pair<String, String>> res = new Vector<>();
        Vector<DVMCompilationOptionsSet> optionsSets = getVectorByFK(dvmSettings_in, DVMCompilationOptionsSet.class);
        Vector<DVMEnvironmentsSet> environmentsSets = getVectorByFK(dvmSettings_in, DVMEnvironmentsSet.class);
        //----
        if (optionsSets.isEmpty() && environmentsSets.isEmpty()) {
            return res;
        }
        int size_ = Math.min(optionsSets.size(), environmentsSets.size());
        for (int i = 0; i < size_; ++i) {
            Vector<DVMCompilationOption> options = getVectorByFK(optionsSets.get(i), DVMCompilationOption.class);
            Vector<DVMEnvironment> environments = getVectorByFK(environmentsSets.get(i), DVMEnvironment.class);
            String optionsLine = printOptionsLine(options);
            String environmentsLine = (i < environmentsSets.size()) ? printEnvironmentsLine(environments) : "";
            res.add(new Pair<>(
                    optionsLine,
                    environmentsLine));
        }
        //дополнения
        if (optionsSets.size() < environmentsSets.size()) {
            for (int i = optionsSets.size(); i < environmentsSets.size(); ++i) {
                res.add(new Pair<>(
                        "",
                        printEnvironmentsLine(getVectorByFK(environmentsSets.get(i), DVMEnvironment.class))
                ));
            }
        } else {
            if (optionsSets.size() > environmentsSets.size()) {
                for (int i = environmentsSets.size(); i < optionsSets.size(); ++i) {
                    res.add(new Pair<>(
                            printOptionsLine(getVectorByFK(optionsSets.get(i), DVMCompilationOption.class)),
                            ""
                    ));
                }
            }
        }
        return res;
    }
    public void Patch() throws Exception {
    }
}
