package TestingSystem.SAPFOR;
import Common.Constants;
import Common.Global;
import Common.Utils.Utils;
import GlobalData.Tasks.TaskState;
import Repository.Component.Sapfor.Sapfor;
import TestingSystem.SAPFOR.Json.SapforConfiguration_json;
import TestingSystem.SAPFOR.Json.SapforVersion_json;
import TestingSystem.SAPFOR.SapforTask.SapforTask;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;

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_2021<SapforTask> {
    @Override
    public String getDescription() {
        return "";
        //    "Запуск задачи SAPFOR"; Оставляем пустое описание чтобы не засорять журнал.
    }
    @Override
    protected boolean needsAnimation() {
        return false;
    }
    //--
    File sapfor_drv;
    SapforConfiguration_json sapforConfiguration_json;
    SapforVersion_json version_json;
    //-----
    File root;
    File parentTask;
    File task;
    //-----
    @Override
    protected boolean canStart(Object... args) throws Exception {
        sapfor_drv = (File) args[0];
        sapforConfiguration_json = (SapforConfiguration_json) args[1];
        target = (SapforTask) args[2];
        version_json = null;
        //--->>
        parentTask = Paths.get(Global.Home, String.valueOf(sapforConfiguration_json.id), target.test_description).toFile();
        root = new File(Global.Home, String.valueOf(sapforConfiguration_json.id));
        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_2021 code) throws Exception {
        task = new File(parentTask, "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_2021.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, ""));
        for (PassCode_2021 code : sapforConfiguration_json.codes) {
            if (parse()) {
                if (code.equals(PassCode_2021.CreateParallelVariants))
                    variants();
                else if (!transformation(code))
                    break;
            } else
                break;
        }
        target.ChangeDate = new Date().getTime();
    }
}
