﻿using UnityEngine;

public static class dfControlExtensions 
{
	//Returns the relative position relative to a control of any point
	//This is just a slightly modified version of getRelativePosition 
	//defined in dfControl.
	public static Vector3 GetRelativePosition(this dfControl control, Vector3 position)
	{
		if (control.transform.parent == null)
		{
			return Vector3.zero;
		}

		if (control.Parent != null)
		{
			var p2u = control.PixelsToUnits();
			var parentPos = control.transform.parent.position;
			var controlPos = position; 

			var relativeTransform = control.transform.parent;

			var relativeParentPos = relativeTransform.InverseTransformPoint(parentPos / p2u);
			relativeParentPos += control.Parent.Pivot.TransformToUpperLeft(control.Parent.Size);

			var relativeControlPos = relativeTransform.InverseTransformPoint(controlPos / p2u);
			relativeControlPos += control.Pivot.TransformToUpperLeft(control.Size);

			var relativePos = relativeControlPos - relativeParentPos;

			return relativePos.Scale(1, -1, 1);
		}

		// Need a reference to the parent Manager in order to proceed
		var view = control.GetManager();
		if (view == null)
		{
			Debug.LogError("Cannot get position: View not found");
			
			return Vector3.zero;
		}

		// Calculate the upper left corner in world-space coordinates
		var pixelSize = control.PixelsToUnits();
		var upperLeft = position + control.Pivot.TransformToUpperLeft(control.Size) * pixelSize;

		// The Manager's clipping planes are ordered left, right, top, bottom
		var planes = view.GetClippingPlanes();
		var x = planes[0].GetDistanceToPoint(upperLeft) / pixelSize;
		var y = planes[3].GetDistanceToPoint(upperLeft) / pixelSize;

		// Return the relative distance from the left and top frustum planes
		return new Vector3(x, y).RoundToInt();
	}
}
