package _VisualDVM.Passes.All;
import _VisualDVM.Global;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.Passes.Sapfor.SapforModification;
import _VisualDVM.ProjectData.SapforData.Arrays.ArrayState;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;

import java.util.Vector;

import static _VisualDVM.ProjectData.SapforData.Arrays.ArrayState.None;
import static _VisualDVM.ProjectData.SapforData.Arrays.ArrayState.Selected;
public class MassSelectArrays extends SapforModification {
    boolean needs_sapfor;
    ArrayState new_state;
    Vector<ProjectArray> arrays;
    @Override
    public boolean needsConfirmations() {
        return false;
    }
    @Override
    protected String getSapforPassName() {
        return "SPF_SetDistributionFlagToArrays";
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        boolean flag = (boolean) args[0];
        if (args[1] instanceof ProjectArray) {
            arrays = new Vector<>();
            arrays.add((ProjectArray) args[1]);
        } else
            arrays = (Vector<ProjectArray>) args[1];
        needs_sapfor = false;
        //---->>
        new_state = flag ? Selected : None;
        if (super.canStart(args)) {
            Vector<String> keys = new Vector<>();
            Vector<String> states = new Vector<>();
            for (ProjectArray array : arrays) {
                if (Global.mainModule.getProject().declaratedArrays.getUI().isObjectVisible(array) && array.isSelectionEnabled()) {
                    keys.add(array.UniqKey);
                    states.add(String.valueOf(new_state.ordinal()));
                }
            }
            if (Global.mainModule.getPass(PassCode.SPF_ParseFilesWithOrder).isDone()) {
                needs_sapfor = true;
                addOpt1 = String.join("|", keys);
                addOpt2 = String.join("|", states);
            }
            return !keys.isEmpty() && !states.isEmpty();
        }
        return false;
    }
    @Override
    protected void body() throws Exception {
        if (needs_sapfor) super.body();
    }
    @Override
    protected void performDone() throws Exception {
        if (needs_sapfor)
            sapfor.ResetAllAnalyses();
        //--
        for (ProjectArray array : arrays) {
            if (
                    Global.mainModule.getProject().declaratedArrays.getUI().isObjectVisible(array) && array.isSelectionEnabled()) {
                array.setState(new_state);
                array.SaveUserState();
            }
        }
    }
    @Override
    protected void showDone() throws Exception {
        target.declaratedArrays.ShowUI();
        target.db.savedArrays.ShowUI();
    }
}