package Visual_DVM_2021.Passes.All;
import Common.Utils.Utils_;
import _VisualDVM.Current;
import _VisualDVM.Global;
import _VisualDVM.Visual.UI;
import Common.Utils.Index;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.Loops.Loop;
import Visual_DVM_2021.Passes.SapforAnalysis;

import java.util.Vector;
public class SPF_GetGraphLoops extends SapforAnalysis {
    @Override
    public String phase() {
        return "LOOP_GRAPH";
    }
    @Override
    protected void showPreparation() {
        if (Global.mainModule.HasFile())
            Global.mainModule.getFile().form.ShowNoLoops();
    }
    @Override
    protected boolean alwaysCheck() {
        return true;
    }
    @Override
    protected boolean isAtomic() {
        return false;
    }
    @Override
    protected void performPreparation() throws Exception {
        super.performPreparation(); //удаление интеррупта.
        target.numLoops = 0;
        for (DBProjectFile file : target.db.files.Data.values()) {
            file.LoopNests.clear();
            file.AllLoops.clear();
            file.LoopGraphTitle = "Всего циклов: 0";
        }
    }
    @Override
    protected void unpack(String packed) throws Exception {
        Vector<String> done_programs = new Vector<>();
        String[] splitedPackedGraph = packed.split("\\|");
        for (int i = 0; i < splitedPackedGraph.length; i += 2) {
            String name_ = Utils_.toW(splitedPackedGraph[i]);
            String[] packedLoopInfo = splitedPackedGraph[i + 1].split("#");
            Index idx = new Index();
            int nests_ = Integer.parseInt(packedLoopInfo[idx.Inc()]);
            DBProjectFile program = target.db.files.Data.get(name_);
            if (!done_programs.contains(name_)) {
                for (int k = 0; k < nests_; ++k) {
                    Loop newLoop = new Loop(packedLoopInfo, idx, program);
                    program.LoopNests.add(newLoop);
                }
                program.LoopGraphTitle = "Всего циклов: " + program.AllLoops.size();
                target.numLoops += program.AllLoops.size();
                done_programs.add(name_);
            }
        }
        target.UpdateLoopsCount();
    }
    @Override
    protected void FocusResult() {
        super.FocusResult();
        if (Global.mainModule.HasFile())
            Global.mainModule.getFile().form.FocusLoops();
    }
    @Override
    protected void showDone() throws Exception {
        UI.getMainWindow().getProjectWindow().getAnalysisWindow().ShowLoopsCount();
        UI.getMainWindow().getProjectWindow().getAnalysisWindow().ShowRegions();
        if (Global.mainModule.HasFile())
            Global.mainModule.getFile().form.ShowLoops();
        super.showDone();
    }
}