/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.karry.dop.core.registers;

import cz.karry.dop.core.*;
import java.util.ArrayList;

/**
 *
 * @author karry
 */
public abstract class Register implements SignalListener{
    
    private int value = 0;
    protected ArrayList<RegisterListener> listeners = new ArrayList<RegisterListener>();
    protected String name;
    protected Signal reset;
    
    Register(String name, Signal reset){
        this.name = name;
        this.reset = reset;
        reset.addSignalListener(this);
    }
    
    public void addChangeListener(RegisterListener listener){
        listeners.add(listener);
    }
    
    public ArrayList<RegisterListener> getChangeListeners(){
        return this.listeners;
    }    
    
    public void setValue(int value){
        if (this.value == value)
            return;

        this.value = value;
        changePerform();
    }
    
    public int getValue(){
        return this.value;
    }
    
    public String getValueStr(){
        return String.valueOf( this.value );
    }
    
    public String getName(){
        return name;
    }
    
    
    public void signalChangePerformed(Signal signal, boolean active) {
        if ((signal==reset) && active){
            value = 0;
            changePerform();
        }
    }

    private void changePerform() {
        for (int i=0; i< listeners.size(); i++){
            listeners.get(i).registerChangePerformed(this,value);
        }
    }
}
