package _VisualDVM.GlobalData.Tasks.Supervisor.Local.Windows;
import Common.Utils.Utils_;
import _VisualDVM.GlobalData.Tasks.Supervisor.Local.LocalTaskSupervisor;
import _VisualDVM.GlobalData.Tasks.Task;
import _VisualDVM.GlobalData.Tasks.TaskState;

import java.util.Date;
import java.util.concurrent.TimeUnit;
//https://ab57.ru/cmdlist/taskkill.html
public abstract class WindowsLocalTaskSupervisor<T extends Task> extends LocalTaskSupervisor<T> {
    @Override
    protected void StartTask() throws Exception {
        super.StartTask();
        task.PID = "start_task_script.bat"; // возможно делать уникальное имя скрипта, чтобы было чем убивать под виндой.
    }
    //--------------------------------------------------->>>
    protected void CheckIfNeedAbort() {
        if (project.getInterruptFile().exists())
            task.state = TaskState.AbortingByUser;
        if (performanceTime > task.maxtime) {
            try {
                AbortTask();
            } catch (Exception ex) {
                Utils_.MainLog.PrintException(ex);
            }
            task.state = TaskState.AbortedByTimeout;
        }
    }
    @Override
    protected void CheckTask() throws Exception {
        if (taskProcess.waitFor(getTaskCheckPeriod(), TimeUnit.SECONDS)) {
            exitCode = taskProcess.waitFor();
            task.state = TaskState.Finished;
        } else {
            performanceTime += getTaskCheckPeriod();
        }
    }
    @Override
    public void WaitForTask() throws Exception {
        if (isTaskActive()) {
            task.StartDate = (new Date()).getTime();
            pass.ShowMessage1("Задача активна");
            RefreshProgress();
            do {
                CheckTask();
                if (isTaskActive()) CheckIfNeedAbort();
                RefreshProgress();
            } while (isTaskActive());
        }
    }
}
