package Visual_DVM_2021.Passes.All;
import Common.Utils.Utils_;
import _VisualDVM.Constants;
import _VisualDVM.Global;
import _VisualDVM.Utils;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Repository.Server.ServerExchangeUnit_2021;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackage.SapforPackage;
import Visual_DVM_2021.Passes.PassCode;
import Common.Passes.Pass;
import Visual_DVM_2021.Passes.Server.TestingSystemPass;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Date;
public class DownloadSapforPackage extends Pass<SapforPackage> {
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    File loaded;
    byte[] packed;
    @Override
    protected boolean canStart(Object... args) throws Exception {
        target = (SapforPackage) args[0];
        if (!target.state.isDone()){
            Log.Writeln_("Возможно загрузить только завершенный пакет.");
            return false;
        }
        int id = target.id;
        loaded = new File(target.getLocalWorkspace(), Constants.LOADED);
        if (!loaded.exists()){
            Pass pass = new TestingSystemPass() {
                @Override
                public String getDescription() {
                     return "Скачивание";
                }
                @Override
                protected void ServerAction() throws Exception {
                    Command(new ServerExchangeUnit_2021(ServerCode.DownloadSapforPackage, "",id));
                    packed = (byte[]) response.object;
                }
            };
            return pass.Do();
        };
        return false;
    }
    @Override
    protected void body() throws Exception {
        File workspace = target.getLocalWorkspace();
        Utils.forceDeleteWithCheck(workspace);
        File archive = Utils.getTempFileName(String.valueOf(target.id));
        Utils_.bytesToFile(packed,archive);
        Global.mainModule.getPass(PassCode.UnzipFolderPass).Do(archive.getAbsolutePath(), Global.SapforPackagesDirectory.getAbsolutePath());
        FileUtils.writeStringToFile(loaded, new Date().toString());
    }
}
