using UnityEngine;

namespace Gamelogic.Grids.Examples
{
	public class TorusPointyHexMap : TransformedMap<PointyHexPoint>
	{
		private class MapData
		{
			private readonly float width;
			private readonly float height;
			private readonly Vector2 smallRadius;
			private readonly Vector2 bigRadius;

			public MapData(
				IGrid<PointyHexPoint> grid, 
				Vector2 cellDimensions,
				Vector2 smallRadius,
				Vector2 bigRadius)
			{
				var map2D = new PointyHexMap(cellDimensions);
				var gridDimensions = map2D.CalcGridDimensions(grid);

				width = gridDimensions.x - cellDimensions.x/2;
				height = gridDimensions.y - cellDimensions.y/4;

				this.smallRadius = smallRadius;
				this.bigRadius = bigRadius;
			}

			public Vector3 To3D(Vector3 v2)
			{
				float smallAngle = Mathf.PI * 2 * v2.y / height;
				float bigAngle = Mathf.PI * 2 * v2.x / width;
			
				float x = (bigRadius.x + smallRadius.x * Mathf.Cos(smallAngle)) * Mathf.Cos(bigAngle);
				float z = (bigRadius.y + smallRadius.x * Mathf.Cos(smallAngle)) * Mathf.Sin(bigAngle);
				float y = smallRadius.y * Mathf.Sin(smallAngle);

				return new Vector3(x, y, z);
			}
		}

		public TorusPointyHexMap(
			IGrid<PointyHexPoint> grid, 
			Vector2 cellDimensions,
			Vector2 smallRadius,
			Vector2 bigRadius) :
				base(
				new PointyHexMeshMap(cellDimensions, new PointyHexMap(cellDimensions)),
				new MapData(grid, cellDimensions, smallRadius, bigRadius).To3D)
		{
		}
	}
}