package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.UI.UI;
import Common.Utils.Utils;
import GlobalData.Machine.MachineType;
import GlobalData.Tasks.RunTask.RunTask;
import GlobalData.Tasks.TaskState;
import ProjectData.Project.db_project_info;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.PassException;
import Visual_DVM_2021.Passes.Pass_2021;

import java.util.Vector;
public class Run extends Pass_2021<db_project_info> {
    Pass_2021 subpass = null;
    Vector<RunTask> runTasks;
    @Override
    public String getIconPath() {
        return "/icons/GreenStart.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    @Override
    protected void performPreparation() throws Exception {
        runTasks = Current.getRunConfiguration().generateRunTasks(target, Current.getCompilationTask());
        for (RunTask runTask : runTasks) {
            Global.db.Insert(runTask);
            Utils.forceDeleteWithCheck(runTask.getLocalWorkspace());
        }
    }
    @Override
    protected void showPreparation() throws Exception {
        Global.db.runTasks.ShowUI();
    }
    @Override
    protected boolean canStart(Object... args) {
        subpass = null;
        if (Current.Check(Log, Current.Project, Current.Machine, Current.User, Current.Makefile, Current.RunConfiguration,
                Current.CompilationTask)) {
            //-
            target = Current.getProject();
            //-
            if (Current.getMachine().type.equals(MachineType.MVS_cluster) &&
                    Current.getRunConfiguration().LauncherCall.isEmpty()
            ) {
                Log.Writeln_("Запуск напрямую на кластере запрещён.Используйте для запуска DVM систему или MPI");
            }
            if (!Current.getCompilationTask().state.equals(TaskState.Done))
                Log.Writeln_("Текущая задача на компиляцию еще не выполнялась, или была завершена с ошибками");
            return Log.isEmpty();
        }
        return false;
    }
    @Override
    protected void body() throws Exception {
        switch (Current.getMachine().type) {
            case Local:
                if (Global.isWindows) {
                    subpass = passes.get(PassCode_2021.WindowsLocalRun);
                } else
                    subpass = passes.get(PassCode_2021.LinuxLocalRun);
                break;
            case Undefined:
                throw new PassException("Запуск не реализован для типа машины " + Utils.DQuotes(Current.getMachine().type));
            case MVS_cluster:
                subpass = passes.get(PassCode_2021.MVSRun);
                break;
            default:
                subpass = passes.get(PassCode_2021.ServerRun);
                break;
        }
        int i = 1;
        RunTask current_task = null;
        for (RunTask task : runTasks) {
            current_task = task;
            boolean task_completed = false;
            task.setProgress(i, runTasks.size());
            //-
            Global.db.runTasks.RefreshUI();
            Global.db.runTasks.SetCurrentObjectUI(task.id);
            //-
            subpass.Do(task, target);
            //-
            switch (task.state) {
                case Done:
                case DoneWithErrors:
                    task_completed = true;
                    if (task.hasDvmSts) {
                        Utils.CheckAndCleanDirectory(Current.getProject().getStatisticDirectory());
                        Pass_2021.passes.get(PassCode_2021.SPF_StatisticAnalyzer).Do(task);
                    }
                    break;
                case Finished:
                case Crushed:
                case AbortedByTimeout:
                    task_completed = true;
                    break;
            }
            //-
            Global.db.runTasks.RefreshUI();
            UI.getDebugWindow().ShowCurrentRunTask();
            //-
            if (!task_completed) break;
            ++i;
        }
        if (current_task!=null){
            UI.getDebugWindow().ShowLastRunTask();
        }
    }
}
