package Visual_DVM_2021.Passes.All;
import Common.Constants;
import Common.Global;
import Common.Utils.Utils;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;
import TestingSystem.Common.TasksPackageState;
import TestingSystem.SAPFOR.SapforPackage.SapforPackage;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
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_2021<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.equals(TasksPackageState.Done)){
            Log.Writeln_("Возможно загрузить только завершенный пакет.");
            return false;
        }
        int id = target.id;
        loaded = new File(target.getLocalWorkspace(), Constants.LOADED);
        if (!loaded.exists()){
            Pass_2021 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.unpackFile(packed,archive);
        passes.get(PassCode_2021.UnzipFolderPass).Do(archive.getAbsolutePath(), Global.SapforPackagesDirectory.getAbsolutePath());
        FileUtils.writeStringToFile(loaded, new Date().toString());
    }
}
