package sim.lib.functions;

import java.awt.*;

import sim.*;
import sim.engine.*;

public class GreaterOrEqualThan extends CompareTo
{
/* ==================================================================
	Creation Part
	================================================================= */
	private static Image ICON = GuiFileLink.getImage("sim/lib/functions/GreaterOrEqualThanIcon.gif");
	
	public Image getIcon()
	{
		return GreaterOrEqualThan.ICON;
	}
	
	public String getBubbleHelp()
	{
		return "Greater or equal than constant";
	}
	
/* ==================================================================
	GUI part
	================================================================= */
	public GreaterOrEqualThan()
	{
		super();
	}
	
	protected Wrapper getCopy()
	{
		GreaterOrEqualThan result = new GreaterOrEqualThan();
		result.changeDelay(this.delay);
		result.setBusSize(this.busSize);
		result.constant = this.constant;
		
		return result;
	}
	
	public void paint(Graphics g)
	{
		// draw if visible
		if(this.isVisible())
		{
			int gridGap = CentralPanel.ACTIVE_GRID.getCurrentGridGap();
			int increment = gridGap / 4;
			
			g.setColor(this.brush);
			
			g.drawRect(0, gridGap, 2 * gridGap - 1, 2 * gridGap - 1);
			
			g.fillRect(gridGap - 1, 0, 3, gridGap);
			g.drawLine(gridGap, 3 * gridGap, gridGap, 4 * gridGap);
			
			g.setFont(new Font(Wrapper.FONT_NAME, Font.PLAIN, 3 * increment));
			
			FontMetrics fm = g.getFontMetrics(g.getFont());
			
			Shape old = g.getClip();
			String toDraw = "> " + Integer.toString(this.constant, 16);
			g.setClip(0, gridGap, 2 * gridGap - 1, 2 * gridGap - 1);
			g.drawString(toDraw, gridGap - fm.stringWidth(toDraw) / 2, 2 * gridGap + fm.getAscent() / 2);
			g.drawString("_", gridGap - fm.stringWidth(toDraw) / 2, 2 * gridGap + fm.getAscent() / 2 - fm.getDescent() + 1);
			g.setClip(old);
		}
	}
	
/* ==================================================================
	Simulation part
	================================================================= */
	public void evaluateOutput(double currentTime, Data[] currentInputs, EnginePeer peer)
	{
		double time = this.delay + currentTime;
		
		boolean foundUndefined = false;
		
		int x = 0;
		int base = 1;
		
		for(int loop = 0; (loop < this.busSize) && (!foundUndefined); loop++)
		{
			if(currentInputs[loop].isUndefined())
				foundUndefined = true;
			else
			{
				if(currentInputs[loop].getValue())
					x = x + base;
			}
			
			base = 2 * base;
		}
		
		if(foundUndefined)
			peer.setOutputPinUndefined(0, time);
		else
			peer.setOutputPinValue(0, x >= this.constant, time);
	}
	
	@Override
	public void writeVHDLEntity(String path) {
		VHDLGeneral.write1busto1bitFunction(path,getVHDLName(),this.busSize,"x >= "+this.constant);
	}

	@Override
	public String getVHDLName() {
		return "GREATEROREQUALTHANbus_ent_" + this.busSize;
	}
}