
package cz.karry.dop.core.alu;

import cz.karry.dop.core.Core;
import cz.karry.dop.core.Signal;
import cz.karry.dop.core.SignalListener;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author karry
 */
class Wen implements SignalListener{
    private Signal enw;
    private boolean dValue = true;
    private boolean dTmpValue = false;
    private Core core;
    private Signal ecw;
    private Signal sww;

    public Wen(Core core) {
        this.core = core;
        try {
            core.getSignal(Core.CLK).addSignalListener(this);
            core.getSignal(Core.RESET).addSignalListener(this);

            sww = core.getSignal(Core.SWW);
            ecw = core.getSignal(Core.ECW);
            ecw.addSignalListener(this);
        } catch (Exception ex) {
            Logger.getLogger(Core.class.getName()).log(Level.SEVERE, null, ex);
        }
        enw = new Signal(Alu.ENW);
        //enw.setState(true);
    }

    Signal getEnw() {
        return enw;
    }

    public void signalChangePerformed(Signal signal, boolean active) {
        if (signal.getName().equals(Core.CLK)){
            if (active){
                if (   ((!sww.isActive()) && (!ecw.isActive()) && dValue ) || 
                        ( ecw.isActive() )  ){
                    dTmpValue = true;
                }else{
                    dTmpValue = false;
                }
            }else{
                dValue = dTmpValue;
                if (ecw.isActive() && dValue){
                    enw.setState(true);
                }else{
                    enw.setState(false);                    
                }
            }
        }
        
        if (signal.getName().equals(Core.ECW)){
            if (active && dValue){
                enw.setState(true);
            }else{
                enw.setState(false);
            }
        }
        
        if (signal.getName().equals(Core.RESET) && active){
            //enw.setState(true);
            dValue = true;
            dTmpValue = false;
        }
    }

}
