package ui.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.ArrayList;

import javax.swing.JPanel;

import classes.Constants;
import classes.HolonBody;
import classes.SubNet;
import ui.controller.Control;
import ui.model.Model;

public class HolonCanvas extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// Rendering
	private Graphics2D g2;

	// Ball objects
	private ArrayList<HolonBody> bodies = new ArrayList<>();
	private HolonBody currentBall;
	private int subCount;

	// Frames
	private int currentFrameRate;

	long previousTime = System.currentTimeMillis();
	long currentTime = previousTime;
	long elapsedTime;
	long totalElapsedTime = 0;
	int frameCount = 0;
	private Dimension center;
	private ArrayList<SubNet> subnets;

	private Control controller;
	private Model model;

	public HolonCanvas(Model mod, Control control) {
		// Wire up Events
		this.controller = control;
		this.model = mod;
		subnets = controller.getSimManager().getSubNets();
		subCount = subnets.size();
		previousTime = System.currentTimeMillis();
		currentTime = previousTime;
		totalElapsedTime = 0;
		frameCount = 0;
	}

	// Start Render and Update Threads

	public void paintComponent(Graphics g) {
		super.paintComponent(g);

		if (!controller.getSimManager().getSubNets().equals(subnets)) {
			subnets = controller.getSimManager().getSubNets();
			subCount = subnets.size();
			bodies = new ArrayList<>();
			createBodies(subCount);
		}

		currentTime = System.currentTimeMillis();
		elapsedTime = (currentTime - previousTime); // elapsed time in seconds
		totalElapsedTime += elapsedTime;

		if (totalElapsedTime > 1000) {
			currentFrameRate = frameCount;
			frameCount = 0;
			totalElapsedTime = 0;
		}

		updateGame(elapsedTime / 1000f);
		render(g);

		try {
			// Thread.sleep(getFpsDelay(maxFrameRate));
			Thread.sleep(5);
		} catch (Exception e) {
			e.printStackTrace();
		}

		previousTime = currentTime;
		frameCount++;
		repaint();
	}

	
	private void createBodies(int subCount) {
		calcCenter();
		
		for(int i = 0; i<subCount; i++){
			HolonBody temp = new HolonBody(center.width+i, center.height+i, subnets.get(i).getObjects().size()*5+10, subnets.get(i).getObjects().size()*5+10, model.getSubNetColors().get(i));
			bodies.add(temp);
		}
	}

	public void render(Graphics g) {
		// System.out.printf("Width: %d Height: %d\n", getWidth(), getHeight());

		// Create BufferStrategy for rendering/drawing
		this.g2 = (Graphics2D) g;

		// Turn on anti-aliasing
		this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		// Render Background
		this.g2.setColor(Color.WHITE);
		this.g2.fillRect(0, 0, getWidth(), getHeight());

		// Render Game Objects
		for (int i = 0; i < subCount; i++) {
			bodies.get(i).draw(this.g2);
		}

		HolonBody tempBall = currentBall;
		if (tempBall != null)
			tempBall.draw(this.g2);

	}

	public void updateGame(float elapsedSeconds) {

		// step the position of movable objects based off their velocity/gravity
		// and elapsedTime
		calcCenter();
		for (int i = 0; i < subCount; i++) {
			bodies.get(i).position.setX((float) (bodies.get(i).position.getX() + (bodies.get(i).velocity.getX() * (elapsedSeconds))
					- ((bodies.get(i).position.getX() - center.getWidth()) / 50)));
			bodies.get(i).position.setY((float) (bodies.get(i).position.getY() + (bodies.get(i).velocity.getY() * (elapsedSeconds))
					- ((bodies.get(i).position.getY() - center.getHeight()) / 50)));

			if (Math.abs(bodies.get(i).velocity.getX()) < Constants.epsilon)
				bodies.get(i).velocity.setX(0);
			if (Math.abs(bodies.get(i).velocity.getY()) < Constants.epsilon)
				bodies.get(i).velocity.setY(0);

		}

		checkCollisions();

	}

	// Insertion sort for Sweep and Prune
	public void insertionSort(ArrayList<HolonBody> a) {
		for (int p = 1; p < subCount; p++) {
			Comparable tmp = a.get(p);
			int j = p;

			for (; j > 0 && tmp.compareTo(a.get(j - 1)) < 0; j--)
				a.set(j, a.get(j - 1));

			a.set(j, (HolonBody) tmp);
		}
	}

	public void checkCollisions() {
		insertionSort(bodies);

		for (int i = 0; i < subCount; i++) {		
			// Ball to Ball collision
			for (int j = i + 1; j < subCount; j++) {
				if ((bodies.get(i).position.getX() + bodies.get(i).getRadius()) < (bodies.get(j).position.getX()
						- bodies.get(j).getRadius()))
					break;

				if ((bodies.get(i).position.getY() + bodies.get(i).getRadius()) < (bodies.get(j).position.getY()
						- bodies.get(j).getRadius())
						|| (bodies.get(j).position.getY() + bodies.get(j).getRadius()) < (bodies.get(i).position.getY()
								- bodies.get(i).getRadius()))
					continue;

				bodies.get(i).resolveCollision(bodies.get(j));

			}
		}

	}

	public void calcCenter() {
		center = this.getSize();
		center.height /= 2;
		center.width /= 2;
	}

}
