package GlobalData.Tasks.Supervisor.Remote;
import Common.Current;
import Common.Utils.Utils;
import GlobalData.RemoteFile.RemoteFile;
import GlobalData.Tasks.RunTask.RunTask;
import GlobalData.Tasks.TaskState;
import com.jcraft.jsch.ChannelSftp;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Vector;
public class ServerRunSupervisor extends RemoteTaskSupervisor<RunTask> {
    @Override
    protected void StartTask() throws Exception {
        String res = "./run";
        String env = String.join(" ", Current.getRunConfiguration().getEnvList());
        if (!env.isEmpty()) res = env + " " + res;
        task.PID = pass.ShellCommand(
                "cd " + Utils.DQuotes(getRemoteProject().full_name),
                "ulimit -s unlimited",
                res);
        task.state = TaskState.Running;
    }
    @Override
    protected void ValidateTaskResults() throws Exception {
        task.AnalyzeResultsTexts(project);
    }
    @Override
    protected void PrepareWorkspace() throws Exception {
        super.PrepareWorkspace();
        //-------------------------
        //удалить старую статистику если оная есть.
        if (!task.last_sts_name.isEmpty()) {
            pass.tryRM(new RemoteFile(getRemoteProject().full_name, task.last_sts_name));
            task.UpdateLastStsName("");
        }
        //-------------------------
        String launchScriptText = getLaunchScriptText();
        RemoteFile launchScript = new RemoteFile(getRemoteProject().full_name, "run");
        pass.sftpChannel.put(
                new ByteArrayInputStream(
                        launchScriptText.getBytes(StandardCharsets.UTF_8)), launchScript.full_name);
        pass.sftpChannel.chmod(0777, launchScript.full_name);
        //-
        //отправить usr.par.
        if (task.hasDVMPar()) {
            File par_text = Utils.CreateTempFile("usr", String.join("\n", task.getRunConfiguration().getParList()));
            pass.putSingleFile(par_text, new RemoteFile(getRemoteProject().full_name, "usr.par"));
        }
    }
    protected String getLaunchScriptText() {
        return getStartCommand();
    }
    @Override
    protected String getCoupDeGrace() {
        return "killall -SIGKILL " + task.getCompilationTask().binary_name;
    }
    @Override
    protected void AchieveResults() throws Exception {
        super.AchieveResults();
        task.parseCleanTime();
        //теперь ищем статистику.
        //статистика
        Vector<ChannelSftp.LsEntry> files = pass.sftpChannel.ls(getRemoteProject().full_name);
        for (ChannelSftp.LsEntry file : files) {
            if (file.getFilename().endsWith("sts.gz+")) {
                task.UpdateLastStsName(file.getFilename());
                break;
            }
        }
        if (!task.last_sts_name.isEmpty()) {
            RemoteFile remote_sts = new RemoteFile(getRemoteProject().full_name, task.last_sts_name);
            task.hasDvmSts = pass.tryGetSingleFileWithMaxSize(remote_sts, task.getLocalStsFile(), 10240);
        }
    }
}
/*
        //ищем GCOV
        if (task.getRunConfiguration().needsGCOV()) {
            pass.ShellCommand("cd " + Utils.DQuotes(getRemoteProject().full_name),
                    "gcov *.gcda -p"
            );
            project.CreateGCOVDirs();
            Vector<RemoteFile> gcov_results = pass.getFilesByExtensions(getRemoteProject(), "gcov");
            for (RemoteFile gcov_file : gcov_results) {
                File local_gcov = Paths.get(project.getGCOVDirectory().getAbsolutePath(),
                        gcov_file.name.replace("#", "\\")).toFile();
                pass.getSingleFile(gcov_file.full_name, local_gcov.getAbsolutePath());
            }
*/