package demo1;

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class MoveablePicture {
	private Component owner;
	private Image img;
	public boolean needUpdate = true;
			
	private int x = 0;		// location
	private int y = 0;		// location
	private int imgWidth = 0;
	private int imgHeight = 0;
		
	/**
	* Konstruktor vyžaduje jako parametr grafického vlastníka (rodiče) objektu,
	* tedy nějakou Componentu na které spočívá.
	*/
	public MoveablePicture(Component owner,Image img) {
		this.owner = owner;
		this.img = img;
		imgWidth = 47; 	// Nahodou to vim :-), je to takhle na pevno kvuli appletu
		imgHeight = 88; // Protoze trida Image spatne vracela velikost obrazku
		System.out.println(x + ":" + y );
	}
		
	public void paint(Graphics g) {
		if (!needUpdate) {
			Rectangle toDraw = g.getClipBounds().intersection(new Rectangle(x,y,imgWidth,imgHeight));
			if (!toDraw.isEmpty()) {
				g.drawImage(img,x,y,imgWidth,imgHeight,null);
			}
		}
		else {
			g.drawImage(img,x,y,imgWidth,imgHeight,null);
			needUpdate = false;
		}
	}
	
	public synchronized void setLocation(int x,int y) {
		int left = (this.x < x ? this.x : x) - 1;
		int up = (this.y < y ? this.y : y) - 1;
		int dx = Math.abs(this.x - x) + 2;
		int dy = Math.abs(this.y - y) + 2;
		this.x = x;
		this.y = y;
		needUpdate = true;
		owner.repaint(left,up,imgWidth+dx,imgHeight+dy);
	}
	public Point getLocation(){
		return new Point(x,y);
	}
}
