package fabrik.simulator.pic16f84;

import fabrik.simulator.pic16f84.interfaces.*;

public class PreScaler extends PICComponent implements PreScalerInterface {

    private final int PSA = 0x3;
    private final int OPTION = 0x81;
    private int scaler;

    public PreScaler () {
        super();
        scaler = 0b111;
    }

    @Override
    public boolean isPrescalerOnTimer(){
        return dataRegister.getDirectBit(OPTION, PSA) == 0;
    }



    @Override
    public int getScaler() {
        return scaler;
    }

    @Override
    public int getFactor() {
        int scale = dataRegister.getDirectRegister(OPTION) & 0b111;
        int timer = isPrescalerOnTimer() ? 1 : 0;
        return (int) Math.pow (2, scale+timer);
    }

    @Override
    public void reset(){
        dataRegister.setDirectBit(OPTION, 0, 0);
        dataRegister.setDirectBit(OPTION, 1, 0);
        dataRegister.setDirectBit(OPTION, 2, 0);
    }

    @Override
    public void resetFromRegister() {
        scaler = getFactor();
    }

    @Override
    public void decrement(boolean manual) {
        scaler--;
        if (scaler == 0) {
            scaler = getFactor();
            timer.increment(manual);
        }
    }

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