package _VisualDVM.Passes.All;
import Common.CommonConstants;
import Common.Utils.Utils_;
import _VisualDVM.Global;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.Passes.Server.TestingServerPass;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackage.SapforPackage;
import _VisualDVM.Utils;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Date;
public class DownloadSapforPackage extends TestingServerPass<SapforPackage> {
    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(), CommonConstants.LOADED);
        return !loaded.exists() && SendRequest(ServerCode.DownloadSapforPackage, "", id);
    }
    @Override
    protected void body() throws Exception {
        packed = (byte[]) request.server_response.object;
        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());
    }
}
