package ui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import main.AppPanel;

public class NotificationManager {

	private NotificationManager() {
		polygon.addPoint(0, AppPanel.HEIGHT);
		polygon.addPoint(AppPanel.WIDTH, AppPanel.HEIGHT);
		polygon.addPoint(AppPanel.WIDTH - 30, AppPanel.HEIGHT - 50);
		polygon.addPoint(30, AppPanel.HEIGHT - 50);

		for (int i = 0; i < polygon.ypoints.length; i++) {
			polygon.ypoints[i] += 60;
		}
	}

	private static NotificationManager nm;

	public static NotificationManager getInstance() {
		if (nm == null)
			nm = new NotificationManager();
		return nm;
	}

	private Polygon polygon = new Polygon();
	private long timer;
	private int delay = 3500;
	private float ySpeed = 2.3f, yOff;

	private boolean isUp;
	private boolean isDown;
	private boolean isShowing;
	private boolean remove;
	private boolean tryingToShow;

	private List<String> messages = new CopyOnWriteArrayList<>();

	public void update() {
		if ((remove || messages.isEmpty()) && polygon.ypoints[0] == AppPanel.HEIGHT) {
			if (!isShowing) {
				ySpeed = 1;
				isDown = true;
			}
		}

		if (!messages.isEmpty() && polygon.ypoints[0] == AppPanel.HEIGHT + 60 && !isShowing) {
			isUp = true;
			ySpeed = -1;
			isShowing = true;
			tryingToShow = false;
		}

		if (isShowing) {
			if (!tryingToShow) {
				timer = System.nanoTime();
				tryingToShow = true;
			}
			long e = (System.nanoTime() - timer) / 1000000;
			if (e > delay) {
				remove = true;
				isShowing = false;
			}
		}

		if (isUp) {
			for (int i = 0; i < polygon.ypoints.length; i++) {
				polygon.ypoints[i] += ySpeed;
			}
			if (polygon.ypoints[0] == AppPanel.HEIGHT) {
				isUp = false;
				polygon.ypoints[0] = AppPanel.HEIGHT;
			}

			yOff += ySpeed;
		}

		if (isDown) {
			for (int i = 0; i < polygon.ypoints.length; i++) {
				polygon.ypoints[i] += ySpeed;
			}
			if (polygon.ypoints[0] == AppPanel.HEIGHT + 60) {
				isDown = false;
				polygon.ypoints[0] = AppPanel.HEIGHT + 60;
				if (remove) {
					messages.remove(0);
				}
			}

			yOff += ySpeed;
		}

	}

	public void draw(Graphics2D g2) {
		Font f = g2.getFont();
		g2.setStroke(new BasicStroke(15));
		g2.setColor(Color.WHITE);
		g2.drawPolygon(polygon);
		g2.setStroke(new BasicStroke(1));
		g2.setColor(new Color(100, 100, 100, 175));
		g2.fillPolygon(polygon);

		g2.setColor(Color.ORANGE);
		g2.setFont(new Font("System", Font.PLAIN, 26));
		if (!messages.isEmpty()) {
			g2.drawString(messages.get(0), AppPanel.WIDTH / 2 - g2.getFontMetrics().stringWidth(messages.get(0)) / 2, AppPanel.HEIGHT - 15 + yOff + 60);
		}

		g2.setFont(f);
	}

	public void queueNotif(String text) {
		messages.add(text);
	}

}
