package _VisualDVM.Passes.Repository;
import Common.CommonConstants;
import Common.Utils.Utils_;
import _VisualDVM.Global;
import _VisualDVM.Passes.ProcessPass;
import _VisualDVM.Utils;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.file.Paths;
import java.util.Vector;
public class DownloadRepositoryPass extends ProcessPass {
    String url;
    String dst_name;
    File dst;
    @Override
    public String getDescription() {
        return "Загрузка репозитория";
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        url = (String) args[0];
        dst_name = (String) args[1];
        dst = new File(Global.RepoDirectory, dst_name);
        return true;
    }
    protected boolean hasSubmodules() {
        return false;
    }
    @Override
    protected void body() throws Exception {
        ShowProgress(1, 0, true);
        Vector<String> scriptLines = new Vector<>();
        File loadedFile = Paths.get(dst.getAbsolutePath(), CommonConstants.LOADED).toFile();
        boolean pull = loadedFile.exists();
        if (pull) {
            System.out.println("PULL");
            scriptLines.add("cd " + dst.getAbsolutePath());
            scriptLines.add("GIT_SSL_NO_VERIFY=true git pull");
        } else {
            Utils.CleanDirectory(dst);
            System.out.println("CLONE");
            scriptLines.add("cd " + Utils_.DQuotes(Global.RepoDirectory.getAbsolutePath()));
            scriptLines.add("GIT_SSL_NO_VERIFY=true git clone " + Utils_.DQuotes(url) + " " + Utils_.DQuotes(dst.getAbsolutePath()));
        }
        if (hasSubmodules()) {
            scriptLines.add("cd " + Utils_.DQuotes(dst));
            scriptLines.add("GIT_SSL_NO_VERIFY=true git submodule update --init");
        }
        PerformScript(String.join("\n", scriptLines));
        if (!pull) {
            FileUtils.write(loadedFile, "");
        }
        ShowProgress(1, 1, true);
    }
}
