package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.UI.UI;
import Common.Utils.Utils;
import TestingSystem.Common.Group.Group;
import TestingSystem.Common.Test.Test;
import TestingSystem.DVM.Configuration.Configuration;
import TestingSystem.DVM.DVMPackage.DVMPackage;
import TestingSystem.DVM.DVMPackage.DVMPackage_json;
import TestingSystem.DVM.DVMTasks.DVMCompilationTask;
import TestingSystem.DVM.DVMTasks.DVMRunTask;
import TestingSystem.Common.TasksPackageState;
import Visual_DVM_2021.Passes.Pass_2021;

import java.util.Vector;
public class AddTasksToDVMPackage extends Pass_2021<DVMPackage> {
    Vector<DVMCompilationTask> tasks;
    int tasks_count;
    @Override
    public String getIconPath() {
        return "/icons/AddTasks.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    //--
    public static String checkFlags(String flags_in) {
        if (!flags_in.contains("-shared-dvm")) {
            if (flags_in.isEmpty())
                return "-shared-dvm";
            else return flags_in + " -shared-dvm";
        } else
            return flags_in;
    }
    public static String checkEnvironments(String environmentsSet_in) {
        if (!environmentsSet_in.contains("DVMH_NO_DIRECT_COPY")) {
            if (environmentsSet_in.isEmpty())
                return "DVMH_NO_DIRECT_COPY=" + Utils.DQuotes("1");
            else
                return environmentsSet_in + " " + "DVMH_NO_DIRECT_COPY=" + Utils.DQuotes("1");
        } else
            return environmentsSet_in;
    }
    //--
    public Vector<DVMCompilationTask> createTasksCGT(
            Configuration configuration,
            Group group,
            Test test
    ) {
        Vector<DVMCompilationTask> compilationTasks = new Vector<>();
        for (String flags : configuration.getFlags()) {
            String checked_flags = checkFlags(flags);
            DVMCompilationTask dvmCompilationTask = new DVMCompilationTask(
                    configuration,
                    group,
                    test,
                    checked_flags
            );
            Vector<String> matrixes = configuration.getMatrixes(test.max_dim);
            Vector<String> environments = configuration.getEnvironments();
            for (String environmentSet : environments) {
                String checkedEnvironments = checkEnvironments(environmentSet);
                if (flags.trim().equalsIgnoreCase("-s")) {
                    dvmCompilationTask.runTasks.add(new DVMRunTask(
                            configuration,
                            group,
                            test,
                            "",
                            checked_flags,
                            checkedEnvironments,
                            configuration.getParamsText(),
                            target.kernels
                    ));
                    tasks_count++;
                } else
                    for (String matrix : matrixes) {
                        dvmCompilationTask.runTasks.add(new DVMRunTask(
                                configuration,
                                group,
                                test,
                                matrix,
                                checked_flags,
                                checkedEnvironments,
                                configuration.getParamsText(),
                                target.kernels));
                        tasks_count++;
                    }
            }
            compilationTasks.add(dvmCompilationTask);
        }
        return compilationTasks;
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        if (Current.Check(Log, Current.DVMPackage)) {
            target = Current.getDVMPackage();
            if (!target.state.equals(TasksPackageState.Draft)) {
                Log.Writeln_("Пакет " + Utils.Brackets(target.id) + " не готовится к публикации!");
                return false;
            }
            //---
            tasks = new Vector<>();
            tasks_count = 0;
            //-----------
            //1, Проверяем выбраны ли конфиги.
            if (Global.testingServer.db.configurations.getCheckedCount() == 0) {
                Log.Writeln_("Не отмечена ни одна конфигурация тестирования.");
                return false;
            }
            if (Global.testingServer.db.groups.getCheckedCount() > 0) {
                //2 Проверяем выбраны ли группы.
                for (TestingSystem.DVM.Configuration.Configuration configuration : Global.testingServer.db.configurations.getCheckedItems()) {
                    for (Group group : Global.testingServer.db.groups.getCheckedItems()) {
                        Vector<Test> groupTests = new Vector<>();
                        Vector<Test> checkedGroupTests = new Vector<>();
                        for (Test test : Global.testingServer.db.tests.Data.values()) {
                            if (test.group_id == group.id) {
                                groupTests.add(test);
                                if (test.isSelected())
                                    checkedGroupTests.add(test);
                            }
                        }
                        if (!groupTests.isEmpty()) {
                            if (checkedGroupTests.isEmpty()) {
                                for (Test test : groupTests)
                                    tasks.addAll(createTasksCGT(configuration, group, test));
                            } else {
                                //добавляем только отмеченные.
                                for (Test test : checkedGroupTests) {
                                    tasks.addAll(createTasksCGT(configuration, group, test));
                                }
                            }
                        }
                    }
                }
            }
            if (tasks.isEmpty()) {
                Log.Writeln_("Не удалось добавить задачи.\n" +
                        "Для создания задач отметьте требуемые конфигурации,\n" +
                        "Отметьте группы, или отдельные тесты в отмеченной текущей группе");
                return false;
            }
            return UI.Question("Будет добавлено " + tasks_count + " задач. Продолжить");
        }
        //
        return false;
    }
    @Override
    protected void body() throws Exception {
        DVMPackage_json json = target.package_json;
        //инициализируем идентификаторы задач.
        for (DVMCompilationTask compilationTask : tasks) {
            //--
            compilationTask.id = json.max_task_id;
            json.max_task_id++;
            //-
            for (DVMRunTask runTask : compilationTask.runTasks) {
                runTask.id = json.max_task_id;
                json.max_task_id++;
                runTask.dvmcompilationtask_id = compilationTask.id;
            }
        }
        json.compilationTasks.addAll(tasks);
        target.tasksCount += tasks_count;
        //target.saveJson();
        Global.testingServer.db.Update(target);
    }
    @Override
    protected void showDone() throws Exception {
        Global.testingServer.db.dvmPackages.ShowUI(target.id);
        Global.testingServer.db.dvmRunTasks.ShowDVMPackage(target);
    }
}
