using UnityEngine;

namespace Gamelogic.Grids.Examples
{
	public class SpherePointyHexMap : TransformedMap<PointyHexPoint>
	{
		private class MapData
		{
			private readonly float height;
			private readonly float width;
			private readonly Vector3 radius;
			private Vector2 cellDimensions;

			public MapData(IGrid<PointyHexPoint> grid, Vector2 cellDimensions, Vector3 radius)
			{
				this.cellDimensions = cellDimensions; 
				
				var map2D = new PointyHexMap(cellDimensions);
				var gridDimensions = map2D.CalcGridDimensions(grid);
				
				width = gridDimensions.x - cellDimensions.x / 2;
				height = gridDimensions.y;

				this.radius = radius;
			}

			public Vector3 To3D(Vector3 point)
			{
				float u = point.x;
				float v = point.y + cellDimensions.y/2;
				float w = point.z;
				
				float tRadiusX = (radius.x + w)* Mathf.Cos((v/height - 0.5f)*Mathf.PI);
				float tRadiusZ = (radius.z + w) * Mathf.Cos((v / height - 0.5f) * Mathf.PI);

				float newY = (radius.y + w) * Mathf.Sin((v / height - 0.5f) * Mathf.PI);

				float newX = tRadiusX * Mathf.Cos(u / width * Mathf.PI * 2);
				float newZ = tRadiusZ * Mathf.Sin(u / width * Mathf.PI * 2);

				return new Vector3(newX, newY, newZ);
				//return new Vector3(u, v, 0);
			}
		}

		public SpherePointyHexMap(IGrid<PointyHexPoint> grid, Vector2 cellDimensions, Vector3 radius) :
			base(
			new PointyHexMeshMap(cellDimensions, new PointyHexMap(cellDimensions)),
			new MapData(grid, cellDimensions, radius).To3D)
		{
		}
	}
}