package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Utils.Utils;
import GlobalData.RemoteFile.RemoteFile;
import Visual_DVM_2021.Passes.SSH.CurrentConnectionPass;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class RemoteInitialiseUser extends CurrentConnectionPass<String> {
    @Override
    protected boolean needsInitialize() {
        return false;
    }
    @Override
    protected void ServerAction() throws Exception {
        String workspace_name = Utils.getDateName("visual_sapfor_workspace");
        target = Utils.toU(Paths.get(sftpChannel.getHome(), workspace_name).toString());
        ShowMessage1("Создание рабочих папок...");
        //-------------------------------------
        sftpChannel.mkdir(target);
        sftpChannel.cd(target);
        sftpChannel.mkdir(projects);
        sftpChannel.mkdir(modules);
        sftpChannel.mkdir(compilers);
        sftpChannel.mkdir(tests);
        //------------------------------------
        sftpChannel.cd(modules);
        ShowMessage1("Закачка модулей...");
        put_resource(launcher_code);
        put_resource(starter_code);
        put_resource(Process_r_header);
        //----------------------------------
        String [] planner_files = new String[]{
          "Array.h",

          "CompilationSupervisor.h",
          "CompilationTask.h",

          "File.h",
          "Global.h",

          "Planner.cpp",

          "RunSupervisor.h",
          "RunTask.h",

          "String.h",
          "Supervisor.h",

          "Task.h",
          "Text.h",
          "Utils.h"
        };
        for (String p: planner_files){
            File local_p = Utils.getTempFileName(p);
            URL u = Utils.class.getResource("/files/Planner/" + p);
            InputStream i = u.openStream();
            Files.copy(i, local_p.toPath(), StandardCopyOption.REPLACE_EXISTING);
            putSingleFile(local_p.getAbsolutePath(), p);
        }
        //-------------------------------------
        ShowMessage1("Сборка модулей...");
        //канал на исполнение независим, поэтому переход в папку отдельный
        Command(
                "cd " + Utils.DQuotes(sftpChannel.pwd()), //нужны ли тут кавычки?
                "g++ " + starter_code + " -o " + starter,
                "g++ " + launcher_code + " -o " + launcher,
                "g++ -o3 Planner.cpp -o " + planner,
                "chmod 0777 " + starter,
                "chmod 0777 " + launcher,
                "chmod 0777 " + planner
        );
        //--------------------------------------
        RemoteFile info = new RemoteFile(target, Current.getAccount().email);
        writeToFile("", info);
    }
}
