package _VisualDVM.GlobalData.Tasks.Supervisor.Remote;
import Common.Utils.Utils_;
import _VisualDVM.GlobalData.Makefile.Makefile;
import _VisualDVM.GlobalData.RemoteFile.RemoteFile;
import _VisualDVM.GlobalData.Tasks.CompilationTask.CompilationTask;
import _VisualDVM.GlobalData.Tasks.TaskState;
import _VisualDVM.Utils;

import java.io.File;
public class RemoteCompilationSupervisor extends RemoteTaskSupervisor<CompilationTask> {
    @Override
    protected void PrepareWorkspace() throws Exception {
        //0. если нет папки с его именем создаем.
        pass.user.connection.MKDIR(getRemoteProject());
        pass.user.connection.SynchronizeProjectSubDirsR(project, project.Home, getRemoteProject(), false);
        pass.user.connection.tryRM(getBinary());
        if (!task.binary_name.isEmpty()) {
            RemoteFile old_binary = new RemoteFile(getRemoteProject().full_name, task.binary_name);
            pass.user.connection.tryRM(old_binary);
        }
        //отправить мейкфайл.
        Makefile makefile = task.getMakefile();
        File makefile_text = Utils.CreateTempFile("makefile", makefile.Generate(project));
        pass.user.connection.putSingleFile(makefile_text, new RemoteFile(getRemoteProject().full_name, "Makefile"));
        //очистить все что связано с gcov
        //файлы gcda, gcno, gcov
        pass.user.connection.deleteFilesByExtensions(getRemoteProject(), "gcda", "gcno", "gcov");
        //очистить служебные файлы.
        super.PrepareWorkspace();
    }
    @Override
    protected void StartTask() throws Exception {
        pass.user.connection.startShellProcess(getRemoteProject(), "PID", getStartCommand());
        task.state = TaskState.Running;
    }
    @Override
    protected void ValidateTaskResults() throws Exception {
        if (pass.user.connection.Exists(getBinary())) {
            RemoteFile renamed_binary = new RemoteFile(getRemoteProject().full_name, Utils_.getDateName("spf_" + getBinary().name));
            pass.user.connection.sftpChannel.rename(getBinary().full_name, renamed_binary.full_name);
            task.binary_name = renamed_binary.name;
            task.state = TaskState.Done;
        } else task.state = TaskState.DoneWithErrors;
        task.AnalyzeResultsTexts(project);
    }
}
