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

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