package fabrik.simulator.pic16f84;

import fabrik.simulator.pic16f84.interfaces.ProgramStackInterface;

import java.util.ArrayList;
import java.util.List;

public class ProgramStack extends PICComponent implements ProgramStackInterface {
    private List<Integer> returnStack = new ArrayList<>(8);
    private int stackIndex = 0;

    private void incIndex(){
        if (stackIndex == 7){
            stackIndex = 0;
        }
        else{
            stackIndex++;
        }
    }

    public void push(int value) {
        if ((returnStack.size() != 8 ) && (returnStack.size() <= stackIndex)){
            returnStack.add(value);
            incIndex();
        }
        else {
            returnStack.set(stackIndex, value);
            incIndex();
        }
    }

    public int pop() {
        stackIndex =  (stackIndex > 0) ? --stackIndex : 7;
        return returnStack.get(stackIndex)-1;
    }

    public void reset (){
        returnStack.clear();
        stackIndex = 0;
    }

    public int getStackPointer(){
        return stackIndex;
    }

    public List<Integer> getStack() {
        return returnStack;
    }

    @Override
    public void initialize(PICComponentLocator locator) {
        super.initialize(locator);
    }
}
