/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package middlewares;

import common.Instruction;
import java.util.LinkedList;

/**
 *
 * @author EUGENIO CARVALHO
 */
public class BlockBaseGroup {

    protected LinkedList<BlockBaseOcorrences> bbs = new LinkedList<>();
    protected BlockBaseOcorrences current = null;
    public Integer currentIndex = 0;
    protected String name;

    BlockBaseGroup(String name) {
        this.name = name;
    }

    public void Init() {
        currentIndex = 0;
        current = bbs.get(currentIndex);
    }

    public boolean NextBlock() {
        currentIndex++;

        if (currentIndex > (bbs.size() - 1)) {
            return false;
        }

        current = bbs.get(currentIndex);
        return true;
    }

    public void RegisterBlock(Integer leader, Integer size) {
        if (current != null) {
            current.CloseAllIntervals();
        }
//        System.out.println("Register block:" + name + "." + bbs.size() + "/" + (size - 1));
        BlockBaseOcorrences c = new BlockBaseOcorrences(name + "." + bbs.size(), leader);
        c.LastPosition = (size - 1);
        current = c;
        bbs.add(c);
    }

    public LinkedList<BlockBaseOcorrences> getBasicBlocks() {
        return bbs;
    }

    public BlockBaseOcorrences getCurrent() {
        return current;
    }

    public void ParseInstruction(Instruction inst, String attrs) throws Exception {
        for (String attr : attrs.split(",")) {
            current.Register(inst, attr);
        }
        current.Position++;
    }

//    public BlockBaseGroup RegisterInstruction(Instruction inst, String attr) {
//        current.Register(inst, attr);
//        return this;
//    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        for (BlockBaseOcorrences blockBaseOcorrences : bbs) {
            sb.append(blockBaseOcorrences).append("\n");
        }

        return sb.toString();
    }

    public void Close() {
        current.CloseAllIntervals();
    }

    public BlockBaseOcorrences Current() {
        return current;
    }

    public LinkedList<BlockBaseOcorrences> getBbs() {
        return bbs;
    }

    public void setBbs(LinkedList<BlockBaseOcorrences> bbs) {
        this.bbs = bbs;
    }

    public Integer getCurrentIndex() {
        return currentIndex;
    }

    public void setCurrentIndex(Integer currentIndex) {
        this.currentIndex = currentIndex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BlockBaseOcorrences getBasicBlocks(Integer i) {
        int index = currentIndex + i;
        if (index > bbs.size() - 1) {
            return null;
        }
        return bbs.get(index);

    }

}
