﻿using UnityEngine;
using System.Collections;

using Augumenta;

/**
 * Collection of utility methods used in the example scripts.
 */
public class AgapiUtils {

	/**
	 * Convert a relative Rect3dF to absolute pixel Rect using
	 * the specified camera.
	 */
	public static Rect EventRect3dFToRect(Rect3dF event_rect, Camera camera) {
		float x = event_rect.left * camera.pixelWidth;
		float y = event_rect.top * camera.pixelHeight;
		float w = event_rect.width * camera.pixelWidth;
		float h = event_rect.height * camera.pixelHeight;
		return new Rect (x, y, w, h);
	}

	/**
	 * Convert a world space point to a screen space point using
	 * the specified camera.
	 */
	public static Vector2 WorldToGUIPoint(Vector3 world, Camera camera) {
		Vector2 screenPoint = camera.WorldToScreenPoint (world);
		screenPoint.y = (float)Screen.height - screenPoint.y;
		return screenPoint;
	}

	/**
	 * Get the game objects bounding rectangle in screen space using
	 * the specified camera.
	 */
	public static Rect GUIRectFromObject(GameObject go, Camera camera) {
		Vector3 cen = go.GetComponent<Renderer> ().bounds.center;
		Vector3 ext = go.GetComponent<Renderer> ().bounds.extents;
		Vector2[] extentPoints = new Vector2[8] {
			WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y - ext.y, cen.z - ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y - ext.y, cen.z - ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y - ext.y, cen.z + ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y - ext.y, cen.z + ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y + ext.y, cen.z - ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y + ext.y, cen.z - ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y + ext.y, cen.z + ext.z), camera),
			WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y + ext.y, cen.z + ext.z), camera),
		};
		Vector2 min = extentPoints [0];
		Vector2 max = extentPoints [0];
		foreach (Vector2 v in extentPoints) {
			min = Vector2.Min (min, v);
			max = Vector2.Max (max, v);
		}
		return new Rect (min.x, min.y, max.x - min.x, max.y - min.y);
	}
}
