package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.UI.UI;
import Common.Utils.Utils;
import GlobalData.RemoteFile.RemoteFile;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.PassException;
import Visual_DVM_2021.Passes.SSH.CurrentConnectionPass;

import java.io.File;
import java.nio.file.Paths;
public class DownloadProject extends CurrentConnectionPass {
    private static final int maxSize = 10240;
    boolean dialogOK = false;
    RemoteFile src;
    RemoteFile remote_archive;
    File local_archive;
    @Override
    protected void ServerAction() throws Exception {
        dialogOK = (UI.getRemoteFileChooser().ShowDialog(getDescription(), this, true));
        if (dialogOK) {
            src = Current.getRemoteFile();
            System.out.println(Current.getRemoteFile());
            remote_archive = new RemoteFile(src.full_name, src.name + ".zip", false);
            local_archive = Utils.getTempFileName(remote_archive.name);
            if ((getFileKBSize(src.full_name)) <= maxSize) {
                ShowMessage2("Запаковка папки проекта..");
                Command(
                        "cd " + Utils.DQuotes(src.full_name),
                        "zip -r " + Utils.DQuotes(remote_archive.full_name) + " ./"
                );
                //  try {
                ShowMessage2("Загрузка проекта..");
                getSingleFile(remote_archive.full_name, local_archive.getAbsolutePath());
                //  } catch (Exception ex) {
                //      throw new PassException("Ошибка загрузки");
                //  }
                sftpChannel.rm(remote_archive.full_name);
            } else throw new PassException("Размер проекта превышает " + maxSize + " KB.\n");
        } else {
            //диалога не вышло, сбрасываем файл.
            Current.set(Current.RemoteFile, null);
        }
    }
    @Override
    protected boolean validate() {
        Current.Check(Log, Current.RemoteFile);
        return (Log.isEmpty());
    }
    @Override
    protected void performDone() throws Exception {
        File project = Paths.get(Global.visualiser.getWorkspace().getAbsolutePath(),
                Utils.getDateName(src.name)).toFile();
        if (passes.get(PassCode_2021.UnzipFolderPass).Do(local_archive.getAbsolutePath(), project.getAbsolutePath())) {
            if (UI.Question("Проект " + Utils.Brackets(src.name) + " успешно загружен. Открыть его"))
                passes.get(PassCode_2021.OpenCurrentProject).Do(project);
        }
    }
}
