package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.Utils.Utils;
import GlobalData.User.User;
import GlobalData.User.UserState;
import Visual_DVM_2021.Passes.ProcessPass;
import Visual_DVM_2021.Passes.SSH.ConnectionPass;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.file.Paths;
public class LocalInitaliseUser extends ProcessPass<User> {
    @Override
    protected boolean canStart(Object... args) throws Exception {
        target = Current.getUser();
        return true;
    }
    @Override
    protected void body() throws Exception {
        File workspace = Paths.get(Global.Home, "User").toFile();
        target.workspace = workspace.getAbsolutePath();
        Utils.CheckAndCleanDirectory(workspace);
        FileUtils.forceMkdir(target.getLocalProjectsDir());
        FileUtils.forceMkdir(target.getLocalModulesDir());
        //-
        if (!Global.isWindows) {
            File headerCode = target.getHeaderCodeFile();
            //-
            File starterCode = target.getStarterCodeFile();
            //-
            File launcherCode = target.getLauncherCodeFile();
            //-
            Utils.CreateResourceFile(headerCode);
            Utils.CreateResourceFile(starterCode);
            Utils.CreateResourceFile(launcherCode);
            //-
            PerformScript(
                    String.join("\n",
                            "cd " + Utils.DQuotes(target.getLocalModulesDir()),
                            "g++ " + ConnectionPass.starter_code + " -o " + ConnectionPass.starter,
                            "chmod 0777 " + ConnectionPass.starter
                    ));
            PerformScript(String.join("\n",
                    "cd " + Utils.DQuotes(target.getLocalModulesDir()),
                    "g++ " + ConnectionPass.launcher_code + " -o " + ConnectionPass.launcher,
                    "chmod 0777 " + ConnectionPass.launcher
            ));
        }
        //-
        target.state = UserState.ready_to_work;
        Global.db.Update(target);
    }
}
