package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Utils.Utils;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;
import TestingSystem.Group.Group;
import TestingSystem.Group.GroupInterface;
import TestingSystem.Test.Test;
import TestingSystem.Test.TestInterface;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.TestingSystemPass;

import java.io.File;
import java.util.Vector;
public class DownloadGroup extends TestingSystemPass<Group> {
    File workspace = null;
    Vector<Test> tests = null;
    @Override
    public String getIconPath() {
        return "/icons/DownloadBugReport.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        workspace = null;
        tests = null;
        if (args.length > 0) {
            target = (Group) args[0];
            workspace = GroupInterface.getLocalWorkspaceD(target);
            return true;
        } else if (Current.Check(Log, Current.Group)) {
            target = Current.getGroup();
            workspace = GroupInterface.getLocalWorkspaceD(target);
            return true;
        }
        return false;
    }
    @Override
    protected void performPreparation() throws Exception {
        //на случай если был открыт какой то из тестов.
        passes.get(PassCode_2021.CloseCurrentProject).Do();
        Utils.CheckAndCleanDirectory(workspace);
        tests = new Vector<>();
        server.db.tests.Data.values().stream().filter(test -> test.group_id.equals(target.id)).forEach(test -> tests.add(test));
    }
    @Override
    protected void ServerAction() throws Exception {
        for (Test test : tests) {
            Command(new ServerExchangeUnit_2021(ServerCode.DownloadTest, test.id));
            response.Unpack(TestInterface.getArchive(test));
        }
    }
    @Override
    protected void performDone() throws Exception {
        super.performDone();
        for (Test test : tests) {
            if (TestInterface.getArchive(test).exists())
                passes.get(PassCode_2021.UnzipFolderPass).Do(
                        TestInterface.getArchive(test).getAbsolutePath(),
                        workspace.getAbsolutePath(), false
                );
        }
    }
}
