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

import java.io.File;
import java.util.Date;
import java.util.Vector;
public class DownloadDVMPackages extends TestingServerPass<Vector<Integer>> {
    Vector<Pair<Integer, Pair<byte[], byte[]>>> packed_packages;
    @Override
    public String getIconPath() {
        return "/icons/DownloadBugReport.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        target = (Vector<Integer>) args[0];
        packed_packages = null;
        return SendRequest(ServerCode.DownloadDVMPackages, "", target);
    }
    @Override
    protected void body() throws Exception {
        packed_packages = (Vector<Pair<Integer, Pair<byte[], byte[]>>>) request.server_response.object;
        ShowMessage1("Распаковка пакета");
        for (Pair<Integer, Pair<byte[], byte[]>> p : packed_packages) {
            DVMPackage dvmPackage = Global.testingServer.db.dvmPackages.get(p.getKey());
            ShowMessage2(String.valueOf(dvmPackage.id));
            File workspace = dvmPackage.getLocalWorkspace();
            Utils_.CheckAndCleanDirectory(workspace);
            File results_zip = new File(workspace, "results.zip");
            File results = new File(workspace, "results");
            File loaded = new File(workspace, CommonConstants.LOADED);
            Pair<byte[], byte[]> packed_package = p.getValue();
            //---
            Utils_.bytesToFile(packed_package.getKey(), results_zip);
            Utils_.bytesToFile(packed_package.getValue(), dvmPackage.getJsonFile());
            Global.mainModule.getPass(PassCode.UnzipFolderPass).Do(results_zip.getAbsolutePath(), workspace.getAbsolutePath());
            FileUtils.writeStringToFile(loaded, new Date().toString());
        }
    }
}
