package IntermediaryCode;

import API.Instruction;
import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 *
 * @author Eugenio
 */
public class CodeOtimizadorProcessor implements CodeProcessing {

    protected Code code;
//    protected ArrayList<Filtros> filtros = new ArrayList<Filtros>();
    protected boolean enable = true;

    public CodeOtimizadorProcessor(boolean enabled) {
        enable = enabled;
    }
//
//    public void otimizar() throws Exception {
//        for (Filtros f : filtros) {
//            f.filtrar(code);
//        }
//    }

    @Override
    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
        if (!enable) {
            return;
        }
        Block block = c.Block();
        Iterator<Instruction> instructions = block.Instructions().iterator();
//        System.out.println("Exec Oti. in block " + block.getName());
        while (instructions.hasNext()) {

            Instruction inst = instructions.next();
            switch (inst.G("type")) {
                case "copy":

                    // Se o destino da copia não for indexado então pode executar 
                    // o replace da ocorrencia e remover a instrucao de copia
//                    if (!inst.eq("dst_indexed", "true") && inst.eq("p1value", "false")) {
                    if (!inst.eq("dst_indexed", "true")) {
//                        System.out.println("Otimizacao - replace " + inst.G("p1") + " -> " + inst.G("dst"));
                        if (inst.eq("p1value", "true")) {
                            block.ReplaceVar(inst.G("dst"), inst.G("p1"));

                        } else {
                            block.ReplaceVar(inst.G("p1"), inst.G("dst"));
                        }
                        block.CurrentAddress--;
                        instructions.remove();
                    }
            }
        }
        c.PosicaoLabel = block.BaseAddress;
        block.Update();
    }
}
