package exercisesinlogic;

import java.util.ArrayList;
import rita.RiText;
import processing.core.PFont;
import processing.core.PApplet;

public class BubbleAttractor {
	public ArrayList<Bubble> bubbles;
	public RiText text;
	public PFont font;
	public int x;
	public int y;
	public static int BUFFER = 10; // buffer around the text in pixels...
	public boolean drawing = true;
	
	public BubbleAttractor(PApplet applet, String text, String fontfile, int x, int y) {
		this.text = new RiText(applet, text);
		this.font = this.text.loadFont(fontfile);
		bubbles = new ArrayList<Bubble>();
	}
	
	public void setX(int x) {
		this.x = x;
		text.setX(x-(text.textWidth()/2));
	}
	
	public void setY(int y) {
		this.y = y;
		text.setY(y+(text.textHeight()/2));
	}
	
	public void addBubble(Bubble bubble) {
		bubbles.add(bubble);
	}
	
	public void removeBubbleWithText(String text) {
		ArrayList<Bubble> to_remove = new ArrayList<Bubble>();
		for (Bubble bubble : bubbles) {
			if( bubble.text.equals(text) ) {
				to_remove.add(bubble);
			}
		}
		for (Bubble bubble : to_remove) {
			bubbles.remove(bubble);
		}
	}
	
	// Arranges the bubbles evenly around the central RiText
	private void updateBubbles() {
		if(bubbles.isEmpty()) {
			return;
		}
		float angle = 0;
		int current_x = (int)(x+text.textWidth()/1.5); // what?
		int current_y = (int)(y-text.textHeight()/3-bubbleWithLargestRadius().radius()-BUFFER); // what?
		float dist = PApplet.dist(x, y, current_x, current_y);
		Bubble current_bubble;
		for(int i = 0; i < bubbles.size(); ++i) {
			current_bubble = bubbles.get(i);
			current_x = (int)(x + dist*PApplet.cos(angle));
			current_y = (int)(y - dist*PApplet.sin(angle));
			current_bubble.setX(current_x);
			current_bubble.setY(current_y);
			angle += (PApplet.TWO_PI) / (bubbles.size());
		}
	}

	public void draw(PApplet applet) {
		if (drawing) {
			text.draw();
			updateBubbles();
			int angle = 0;
			for (int i = 0; i < bubbles.size(); ++i) {
				if (angle >= PApplet.PI / 2 && angle <= PApplet.PI * (3 / 2)) {
					bubbles.get(i).draw(applet, angle + PApplet.PI / 2,
							-1 * PApplet.PI);
				} else {
					bubbles.get(i).draw(applet, angle, -1 * PApplet.PI);
				}				angle += (PApplet.TWO_PI) / (bubbles.size());
			}
		}
	}

	public Bubble pointInside(int x, int y) {
		for (Bubble bubble : bubbles) {
			if( bubble.pointInside(x, y) ) {
				return bubble;
			}
		}
		return null;
	}
	
	public Bubble bubbleWithLargestRadius() {
		float current_largest_radius = 0;
		Bubble current_bubble = null;
		for (Bubble bubble : bubbles) {
			float radius = bubble.radius();
			if(radius > current_largest_radius) {
				current_largest_radius = radius;
				current_bubble = bubble;
			}
		}
		return current_bubble;
	}
}
