﻿using System.Collections.Generic;
using Gamelogic.Grids;
using UnityEngine;

public class HexLinesGrid : GridBehaviour<PointyHexPoint>
{
	private PointyHexPoint startNode;
	private PointyHexPoint endNode;


	public override void InitGrid()
	{
		startNode = PointyHexPoint.Zero;
		endNode = PointyHexPoint.NorthWest;

		UpdatePresentation();
	}

	public void OnLeftClick(PointyHexPoint clickedPoint)
	{
		Debug.Log("Called");
		startNode = clickedPoint;

		UpdatePresentation();
	}

	public void OnRightClick(PointyHexPoint clickedPoint)
	{
		endNode = clickedPoint;

		UpdatePresentation();
	}

	private void UpdatePresentation()
	{
		var line = GetLine(startNode, endNode);

		foreach (var point in Grid)
		{
			Grid[point].Color = line.Contains(point)
				? GridBuilderUtils.DefaultColors[2]
				: GridBuilderUtils.DefaultColors[0];

			/**
				This part is necessary because SpriteCells
				highlight by default when clicked.
			*/
			var cell = Grid[point] as SpriteCell;

			if (cell != null)
			{
				cell.HighlightOn = false;
			}
		}
	}

	List<PointyHexPoint> GetLine(PointyHexPoint p1, PointyHexPoint p2)
	{
		int distance = p1.DistanceFrom(p2);

		var line = new List<PointyHexPoint>();

		if (distance == 0)
		{
			line.Add(p1);

			return line;
		}

		for (int i = 0; i <= distance; i++)
		{
			var t = i / (float)distance;
			var point = Map[Map[p1] * (1 - t) + Map[p2] * t];  //It's almost surely possible to optimize this line if necessary
			line.Add(point);
		}

		return line;
	}
}
