package IntermediaryCode;

/*
 * 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.
 */
import API.Instruction;
import API.Utils;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;

/**
 *
 * @author EUGENIO CARVALHO
 */
public class OcorrenceFinderProcessor implements CodeProcessing {

    protected HashMap<String, BlockOcorrences> blocks = new HashMap<>();
    protected BlockOcorrences block;
    public static Pattern addresspattern = Pattern.compile("\\_[VTGC].*", Pattern.CASE_INSENSITIVE);

    public HashMap<String, BlockOcorrences> getBlocks() {
        return blocks;
    }

    public void setBlocks(HashMap<String, BlockOcorrences> blocks) {
        this.blocks = blocks;
    }

    public BlockOcorrences getBlock() {
        return block;
    }

    public void setBlock(BlockOcorrences block) {
        this.block = block;
    }

    public static Pattern getAddresspattern() {
        return addresspattern;
    }

    public static void setAddresspattern(Pattern addresspattern) {
        OcorrenceFinderProcessor.addresspattern = addresspattern;
    }

    public OcorrenceFinderProcessor() {
    }

    @Override
    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
        String name = c.Block().getName();
        block = new BlockOcorrences(name);
        blocks.put(name, block);

        block.LastPosition = c.Block().CurrentAddress - 1;

        for (Instruction x : c.Block().Instructions()) {
            switch (x.G("type")) {
                case "label":
                    break;
                case "call":
                    block.CloseAllIntervals();
                default:
                    block.Register(x, "dst");
                    block.Register(x, "p1");
                    block.Register(x, "p2");
                    block.Position++;
            }
        }
        // Retorna para o ultimo endereco;
        block.Position--;
        // Atualiza todos os encerramentos de intervalo para a ultima ocorrencia da variavel;
        block.CloseAllIntervals();

    }

    public static boolean IsAddress(String alias) {
//        System.out.println("Is Address:" + alias + "::" + addresspattern.matcher(alias).matches());
        return !Utils.Empty(alias) && addresspattern.matcher(alias).matches();
    }
}
