package lu.tudor.santec.gecamed.formeditor.gui.component;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import com.jgoodies.forms.layout.FormLayout;

public class BackgroundPanel extends JPanel {
	
	private static final long serialVersionUID = 1L;
	
	private byte[] backgroundBytes;
	private Image backgroundImage;
	
	private int x;
	private int y;
	private int w;
	private int h;
	
	private boolean stretchBackground;
	private boolean center;
	
	public BackgroundPanel () {
		super();
	}
	
	public BackgroundPanel (FormLayout layout) {
		super(layout);
	}
	
	public BackgroundPanel (FormLayout layout, byte[] background) {
		super(layout);
		
		setBackgroundImage(background);
	}
	
	
	public void setBackgroundImage (byte[] backgroundImageBytes) {
		this.backgroundBytes = backgroundImageBytes;
		if (backgroundImageBytes != null) {
			this.backgroundImage = new ImageIcon(backgroundImageBytes).getImage();
		} else {
			this.backgroundImage = null;
			
			x = 0;
			y = 0;
			w = 0;
			h = 0;
		}
	}
	
	public Image getBackgroundImage () {
		return backgroundImage;
	}
	
	public byte[] getBackgroundImageBytes () {
		return backgroundBytes;
	}
	
	public void setBackgroundImageX (int x) {
		this.x = x;
	}
	
	public void setBackgroundImageY (int y) {
		this.y = y;
	}
	
	public void setBackgroundImageWidth (int width) {
		this.w = width;
	}
	
	public void setBackgroundImageHeight (int height) {
		this.h = height;
	}
	
	public void setStretched (boolean stretch) {
		this.stretchBackground = stretch;
	}
	
	public boolean isStretched () {
		return this.stretchBackground;
	}
	
	public void setCentered (boolean centered) {
		this.center = centered;
	}
	
	public boolean isCentered () {
		return this.center;
	}
	
	@Override
	public void paintComponent (Graphics g) 
	{
		if (backgroundImage != null) 
		{
			Dimension s = this.getSize();
			if (w < 0 || w > s.width)
				w = s.width;
			if (h < 0 || h > s.height) 
				h = s.height;
			
			if (stretchBackground) 
				g.drawImage(getBackgroundImage(), x, y, w, h, null);
//			else if (center)
//				drawImageCentered();
			else 
				g.drawImage(getBackgroundImage(), x, y, w+x, h+y, 0, 0, w, h, null);
		}
	}
}
