using UnityEngine;

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

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

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

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

			public Vector3 To3D(Vector3 v2)
			{
				var v = new Vector2(v2.x / width, v2.y / height);
				float angle = v.x * Mathf.PI * 2;

				float smallCircleX1 = smallRadius.x * Mathf.Cos(halfTwistCount * angle / 2);

				float x1 = (bigRadius.x + smallCircleX1) * Mathf.Cos(angle * 2);
				float y1 = smallRadius.y * Mathf.Sin(halfTwistCount * angle / 2); //smallCircleY
				float z1 = (bigRadius.y + smallCircleX1) * Mathf.Sin(angle * 2);

				float smallCircleX2 = -smallRadius.x * Mathf.Cos(halfTwistCount * angle / 2);

				float x2 = (bigRadius.x + smallCircleX2) * Mathf.Cos(angle * 2);
				float y2 = -smallRadius.y * Mathf.Sin(halfTwistCount * angle / 2); //smallCircleY
				float z2 = (bigRadius.y + smallCircleX2) * Mathf.Sin(angle * 2);

				var position1 = new Vector3(x1, y1, z1);
				var position2 = new Vector3(x2, y2, z2);

				return Vector3.Lerp(position1, position2, v.y);
			}
		}

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