import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

// Representation graphique d'un pin, herite de Clip 
public class GPin extends Clip {
	
	// Taille par defaut du pin
	public static int DEFAULT_PIN_SIZE = 15;
	
	// Pin lie
	Pin pin;
	
	// Police de caractere pour afficher le nom du pin
	Font font_name;
	
	// CircuitElement parent
	GCircuitElement parent;
	
	// Constructeur (circuitelement parent, zone du pin, pin lie)
	public GPin(GCircuitElement parent, Rectangle zone, Pin pin){
		super(parent.canvas, false);
		
		this.zone = zone;
		this.parent = parent;
		
		this.pin = pin;
		this.pin.addPinListener(pinListener);
		this.x = zone.x;
		this.y = zone.y;
		this.width = zone.width;
		this.height = zone.height;
		
		initImg();
	}
	
	// Destructeur
	public void Dispose(){
		if(isDisposed) return;
		super.Dispose();
		this.pin.remPinListener(pinListener);
		pinListener = null;
	}

	// Ecouteur du pin
	private Pin.PinListener pinListener = new Pin.PinListener() {
		public void stateChanged(Pin pin) {
			Invalidate(); // Changement d'etat -> Invalide le clip
		}

		public void disposed(Pin pin) {
			parent.Dispose(); // Destruction du pin -> Auto destruction
		}

		public boolean askState(Pin pin) { // Le pin demande quel valeur il doit avoir
			return false;	// Ici, on ne sait pas
		}
	};
	
	
	// Initialisation de l'aimge
	public void initImg(){
		if(isDisposed) return;
		
		font_name = new Font("ARIAL", Font.BOLD, 28);
		
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D gg = (Graphics2D)img.getGraphics();
		gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		
		gg.setColor(new Color(220, 220, 220));
		gg.fillRect(0, 0, width, height);
		
		gg.dispose();
		i_base = img;
	}
	
	public void repaint(Graphics2D g) {
		if(isDisposed) return;
		try{
			if(isHover()){
				g.setColor(Color.pink);
				g.setFont(font_name);
				g.drawString(pin.name, parent.x+x+width, parent.y+y+height);
				g.setColor(new Color(40, 40, 220));
				g.fillRect(parent.x+x, parent.y+y, width, height);
			}else if(pin != null && !pin.isDisposed() && pin.isOn()){
				g.setColor(Color.green);
				g.fillRect(parent.x+x, parent.y+y, width, height);
			}
		}catch(Exception ex){}
	}
	
	public boolean hitTest(int x, int y){
		if(isDisposed) return false;
		x -= parent.x - this.x;
		y -= parent.y - this.y;
		return (x >= zone.x && x<=zone.x+zone.width &&
				y >= zone.y && y<=zone.y+zone.height);
	}
	
	public boolean isHover(){
		if(isDisposed) return false;
		return (((CircuitCanvas) canvas).getHoverClip() == this);
	}
	
	public Object getItem(MouseEvent me){
		if(isDisposed) return null;
		if(hitTest(me.getPoint().x - x, me.getPoint().y - y)) return this;
		return null;
	}
}
