package _VisualDVM.GlobalData.Tasks.Supervisor.Remote;
import Common.MainModule_;
import _VisualDVM.GlobalData.RemoteFile.RemoteFile;
import _VisualDVM.GlobalData.RunConfiguration.RunConfiguration;
import _VisualDVM.GlobalData.Tasks.RunTask.RunTask;
import _VisualDVM.GlobalData.Tasks.TaskState;
import _VisualDVM.Utils;
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(" ", MainModule_.instance.getDb().getTable(RunConfiguration.class).getUI().getCurrent().getEnvList());
        if (!env.isEmpty()) res = env + " " + res;
        //--
        //  task.PID =
        pass.user.connection.startShellProcess(getRemoteProject(), "PID", 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.user.connection.tryRM(new RemoteFile(getRemoteProject().full_name, task.last_sts_name));
            task.UpdateLastStsName("");
        }
        //-------------------------
        String launchScriptText = getLaunchScriptText();
        RemoteFile launchScript = new RemoteFile(getRemoteProject().full_name, "run");
        pass.user.connection.sftpChannel.put(
                new ByteArrayInputStream(
                        launchScriptText.getBytes(StandardCharsets.UTF_8)), launchScript.full_name);
        pass.user.connection.sftpChannel.chmod(0777, launchScript.full_name);
        //-
        //отправить usr.par.
        if (task.hasDVMPar()) {
            File par_text = Utils.CreateTempFile("usr", String.join("\n", task.getRunConfiguration().getParList()));
            pass.user.connection.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.user.connection.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.user.connection.tryGetSingleFileWithMaxSize(remote_sts, task.getLocalStsFile(), 10240);
        }
    }
}