package _VisualDVM.GlobalData.Tasks.Supervisor.Local.Linux;
import Common.CommonConstants;
import Common.Utils.Utils_;
import _VisualDVM.Constants;
import _VisualDVM.GlobalData.Tasks.Supervisor.Local.LocalTaskSupervisor;
import _VisualDVM.GlobalData.Tasks.Task;
import _VisualDVM.GlobalData.Tasks.TaskState;
import _VisualDVM.GlobalData.User.User;
import _VisualDVM.Utils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
public abstract class LinuxLocalTaskSupervisor<T extends Task> extends LocalTaskSupervisor<T> {
    @Override
    protected void StartTask() throws Exception {
        super.StartTask();
        task.PID = Utils.readLine(taskProcess);
    }
    @Override
    protected String getScriptText() {
        User user = task.getUser();
        return
                String.join(" ",
                        Utils_.DQuotes(user.getStarterFile()),
                        Utils_.DQuotes(user.getLauncherFile()),
                        String.valueOf(task.maxtime),
                        Utils_.DQuotes(getCoupDeGrace()),
                        task.getFullCommand()
                );
    }
    @Override
    protected void CheckTask() throws Exception {
        if (getDONE_file().exists())
            task.state = TaskState.Finished;
        else if (getTIMEOUT_file().exists())
            task.state = TaskState.AbortedByTimeout;
    }
    @Override
    protected String getKillCommand() {
        return "kill -2 " + task.PID;
    }
    @Override
    public void WaitForTask() throws Exception {
        if (isTaskActive()) {
            //  if (task.PID.isEmpty())
            //      throw new PassException("Ошибка при старте : идентификатор задачи не определен.");
            task.StartDate = (new Date()).getTime();
            pass.ShowMessage1("Задача активна, идентификатор " + Utils_.Brackets(task.PID));
            RefreshProgress();
            do {
                Thread.sleep(getTaskCheckPeriod() * 1000L);
                performanceTime += getTaskCheckPeriod();
                CheckTask();
                if (isTaskActive()) CheckIfNeedAbort();
                RefreshProgress();
            } while (isTaskActive());
        }
    }
    protected File getProjectTime() {
        return Paths.get(getProjectCopy().getAbsolutePath(), Constants.time_file).toFile();
    }
    protected File getDONE_file() {
        return Paths.get(getProjectCopy().getAbsolutePath(), CommonConstants.DONE).toFile();
    }
    protected File getTIMEOUT_file() {
        return Paths.get(getProjectCopy().getAbsolutePath(), CommonConstants.TIMEOUT).toFile();
    }
    @Override
    protected void PrepareWorkspace() throws Exception {
        super.PrepareWorkspace();
        Utils_.forceDeleteWithCheck(getDONE_file());
        Utils_.forceDeleteWithCheck(getTIMEOUT_file());
        Utils_.forceDeleteWithCheck(getProjectTime());
    }
    @Override
    protected void CalculatePerformanceTime() throws Exception {
        Files.move(getProjectTime().toPath(), task.getTimeFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
        task.RefreshTime();
    }
}
