package gos;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

public class FlexiUnit extends Entity {

	private float dx;
	private float dy;

	private BufferedImage img;
	private float raduis;

	public FlexiUnit(float x, float y, UnitType type) {
		super(type, x, y);
	}

	@Override
	public void update() {
		
		if (isDoneMoving) {
			return;
		}

		if (isTargetPicked) {
			move();
			return;
		}

		if (!isActive && isTargetPicked) {
			move();
		}

		if (!isActive)
			return;

		if (isActive && !isTargetPicked)
			return;

		move();
	}

	private void move() {
		dx = tx - x;
		dy = ty - y;
		
		if(dx == 0) {
			dx += 0.5f;
		}
		
		if(dy == 0) {
			dy += 0.5f;
		}

		double dMag = Math.sqrt(dx * dx + dy * dy);

		if (dMag < 2.5) {
			dx = 0;
			dy = 0;
			isActive = false;
			isTargetPicked = false;
			isDoneMoving = true;
		}

		dx /= dMag;
		dy /= dMag;

		x += dx * 2.45f;
		y += dy * 2.45f;
	}

	@Override
	public void mouseMoved(int x, int y) {
		if (isTargetPicked)
			return;
		tx = x- (int) raduis;
		ty = y- (int) raduis;
	}

	@Override
	public void draw(Graphics2D g2) {
		g2.drawImage(img, (int) x, (int) y, null);

		g2.setColor(Color.RED);
		if (isActive) {
			g2.drawOval((int) x, (int) y, (int) raduis * 2, (int) raduis * 2);

			if (!isDoneMoving && !isTargetPicked) {
				g2.setColor(new Color(255, 255, 255, 150));
				g2.fillOval((int) (x - type.getSpeed() / 2 + raduis), (int) (y - type.getSpeed() / 2 + raduis), (int) type.getSpeed(), (int) type.getSpeed());
			}

			if (!hasAttacked && (Math.sqrt(dx * dx + dy * dy) == 0)) {
				g2.setColor(new Color(255, 100, 100, 150));
				g2.fillOval((int) (x - type.getAttackRadius() / 2 + raduis), (int) (y - type.getAttackRadius() / 2 + raduis), (int) type.getAttackRadius(), (int) type.getAttackRadius());
			}
			
			g2.setColor(Color.RED);
			
			if (isActive && !isDoneMoving) {
				g2.drawLine((int) x + (int) raduis, (int) y + (int) raduis, (int) tx+ (int) raduis, (int) ty+ (int) raduis);
			}
		}
	}

	@Override
	public void moveTo(int x, int y) {
		if (isTargetPicked)
			return;
		isTargetPicked = true;
		this.tx = x;
		this.ty = y;
	}

	@Override
	public void attack(Entity e) {

	}

	@Override
	public void setImage(BufferedImage img) {
		this.img = img;
		this.raduis = img.getWidth() / 2;
	}

	@Override
	public float getRadius() {
		return raduis;
	}

}
