package _VisualDVM.TestingSystem.SAPFOR;
import Common.Passes.Pass;
import Common.Utils.Utils_;
import _VisualDVM.ComponentsServer.Component.Sapfor.Sapfor;
import _VisualDVM.Constants;
import _VisualDVM.GlobalData.Tasks.TaskState;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.TestingSystem.SAPFOR.Json.SapforVersion_json;
import _VisualDVM.TestingSystem.SAPFOR.SapforTask.SapforTask;
import _VisualDVM.Utils;

import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Vector;
public class PerformSapforTask extends Pass<SapforTask> {
    //--
    File sapfor_drv;
    SapforVersion_json version_json;
    //-----
    File root;
    File parentTask;
    File task;
    @Override
    public String getDescription() {
        return "";
        //    "Запуск задачи SAPFOR"; Оставляем пустое описание чтобы не засорять журнал.
    }
    @Override
    protected boolean needsAnimation() {
        return false;
    }
    //-----
    @Override
    protected boolean canStart(Object... args) throws Exception {
        //--
        target = (SapforTask) args[0];
        sapfor_drv = (File) args[1];
        //--
        version_json = null;
        //--->>
        parentTask = Paths.get(Utils_.getHomePath(),
                String.valueOf(target.set_id),
                String.valueOf(target.sapfor_configuration_id),
                target.test_description).toFile();
        root = Paths.get(Utils_.getHomePath(), String.valueOf(target.set_id), String.valueOf(target.sapfor_configuration_id)).toFile();
        task = null;
        //--->>
        return true;
    }
    protected boolean parse() throws Exception {
        if (Sapfor.parse(sapfor_drv, parentTask, target.flags)) {
            return true;
        } else {
            target.state = TaskState.DoneWithErrors;
            return false;
        }
    }
    //слегка изменить подход.
    protected boolean transformation(PassCode code) throws Exception {
        task = new File(parentTask, code.equals(PassCode.SPF_SharedMemoryParallelization) ? "p1" : "v1");
        Utils_.CheckAndCleanDirectory(task); //папка для преобразования.
        //если версия пустая, это тоже результат тестирования. Поэтому должна учитываться в древе.
        target.versions.add(version_json = new SapforVersion_json(
                root.getAbsolutePath(),
                task.getAbsolutePath(), code.getDescription()));
        //---
        if (Sapfor.performScript(
                "transformation",
                sapfor_drv,
                parentTask,
                code.getTestingCommand() + " -F " + Utils_.DQuotes(task.getAbsolutePath()),
                target.flags,
                Constants.out_file,
                Constants.err_file
        )) {
            target.state = TaskState.Done;
            parentTask = task;
            return true;
        }
        target.state = TaskState.DoneWithErrors;
        return false;
    }
    protected void variants() throws Exception {
        //папки вариантов создается самим сапфором.
        target.state = Sapfor.performScript(
                "create_variants",
                sapfor_drv,
                parentTask,
                " -t 13 -allVars",// -tinfo",
                target.flags,
                Constants.out_file,
                Constants.err_file
        ) ? TaskState.Done : TaskState.DoneWithErrors;
        //найти папки с вариантами.
        File[] files_ = parentTask.listFiles((dir, name) -> dir.isDirectory() && Utils.isParallelVersionName(name));
        if ((files_ != null) && (files_.length > 0)) {
            Vector<File> files = new Vector<>(Arrays.asList(files_));
            files.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getName().substring(1))));
            for (File file : files)
                target.variants.add(
                        new SapforVersion_json(
                                root.getAbsolutePath(),
                                file.getAbsolutePath(), PassCode.SPF_CreateParallelVariant.getDescription()));
        }
    }
    //-------------------------------------------------->>
    @Override
    protected void body() throws Exception {
        target.StartDate = new Date().getTime();
        target.versions.add(version_json = new SapforVersion_json(target.test_description, "исходная"));
        String[] data = target.codes.split(" ");
        for (String code_s : data) {
            PassCode code = PassCode.valueOf(code_s);
            //--
            if (parse()) {
                if (code.equals(PassCode.CreateParallelVariants))
                    variants();
                else if (!transformation(code))
                    break;
            } else
                break;
            //--
        }
        target.ChangeDate = new Date().getTime();
    }
}
