package GlobalData.Tasks.Supervisor.Local.Linux;
import Common.Constants;
import Common.Utils.Utils;
import GlobalData.Tasks.Supervisor.Local.LocalTaskSupervisor;
import GlobalData.Tasks.Task;
import GlobalData.Tasks.TaskState;
import GlobalData.User.User;
import Visual_DVM_2021.Passes.PassException;

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(), Constants.DONE).toFile();
    }
    protected File getTIMEOUT_file() {
        return Paths.get(getProjectCopy().getAbsolutePath(), Constants.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();
    }
}
