package ui;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class TextPanel implements UIElement {

	private Rectangle bounds;

	protected String text;
	protected Font font;

	protected Color bg_color;
	protected Color fnt_color;

	public TextPanel(int x, int y, int w, int h) {
		this.bounds = new Rectangle(x, y, w, h);
		bg_color = Color.BLACK;
		fnt_color = Color.WHITE;
		text = "Text Panel";
		font = new Font("System", Font.PLAIN, 16);
	}

	@Override
	public void update() {

	}

	@Override
	public void draw(Graphics2D g2) {
		g2.setColor(bg_color);
		g2.fillRoundRect(bounds.x - 15, bounds.y, bounds.width + 30, bounds.height, 20, 20);

		g2.setFont(font);
		g2.setColor(fnt_color);
		List<String> lines = wrap(text, g2.getFontMetrics(), bounds.width - 8);
		for (int i = 0; i < lines.size(); i++) {
			g2.drawString(lines.get(i), bounds.x + 8, bounds.y + (i * 15) + 15);
		}
	}

	@Override
	public Rectangle getBounds() {
		return bounds;
	}

	@Override
	public void mousePressed(MouseEvent e) {

	}

	@Override
	public void mouseReleased(MouseEvent e) {

	}

	@Override
	public void mouseMoved(MouseEvent e) {

	}

	public TextPanel setFnt_color(Color fnt_color) {
		this.fnt_color = fnt_color;
		return this;
	}

	public TextPanel setBg_color(Color bg_color) {
		this.bg_color = bg_color;
		return this;
	}

	public TextPanel setText(String text) {
		this.text = text;
		return this;
	}

	public TextPanel setFont(Font font) {
		this.font = font;
		return this;
	}

	private List<String> wrap(String txt, FontMetrics fm, int maxWidth) {
		StringTokenizer st = new StringTokenizer(txt);

		List<String> list = new ArrayList<String>();
		String line = "";
		String lineBeforeAppend = "";
		while (st.hasMoreTokens()) {
			String seg = st.nextToken();
			lineBeforeAppend = line;
			line += seg + " ";
			int width = fm.stringWidth(line);
			if (width < maxWidth) {
				continue;
			} else { // new Line.
				list.add(lineBeforeAppend);
				line = seg + " ";
			}
		}
		// the remaining part.
		if (line.length() > 0) {
			list.add(line);
		}
		return list;
	}
}
