﻿using Gamelogic.Grids;
using UnityEditor;
using UnityEngine;

namespace Gamelogic.Grids.Examples
{
	public class TrianglePuzzleGame : GridBehaviour<FlatTriPoint>
	{
		public Piece triangle;
		public Piece diamond;

		public GameObject pieceRoot;

		private static readonly PiecePoints Triangle = new PiecePoints
		{
			new FlatTriPoint(0, 0, 0),
			new FlatTriPoint(0, 0, 1),
			new FlatTriPoint(1, 0, 0),
			new FlatTriPoint(0, 1, 0)
		};

		private static readonly PiecePoints Diamond = new PiecePoints
		{
			new FlatTriPoint(0, -1, 1),
			new FlatTriPoint(0, 0, 0),
		};

		private FlatTriGrid<TrianglePuzzleCell> triGrid;

		public override void InitGrid()
		{
			//Cast the values in the grid to our own type
			//Also cast the IGrid to a FlatTriGrid
			triGrid = (FlatTriGrid<TrianglePuzzleCell>) Grid.CastValues<TrianglePuzzleCell, FlatTriPoint>();

			foreach (var point in triGrid)
			{
				triGrid[point].CellType = CellTypeExtensions.ChooseRandom();
				triGrid[point].CellFunction = CellFunction.Board;
			}


		}

		public void Start()
		{
			MakeNextPiece();
		}

		public void Update()
		{
			if (Input.GetKeyDown(KeyCode.Space))
			{
				MakeNextPiece();
			}
		}

		public void MakeNextPiece()
		{
			if (Application.isPlaying)
			{
				pieceRoot.transform.DestroyChildren();
			}
			else
			{
				pieceRoot.transform.DestroyChildrenImmediate();
			}

			var nextPiece = Instantiate((Random.Range(0, 2) == 0) ? triangle : diamond);

			nextPiece.TrianglePuzzleGame = this;

			nextPiece.transform.parent = pieceRoot.transform;
			nextPiece.transform.localScale = Vector3.one;
			nextPiece.transform.localPosition = Vector3.zero;

			nextPiece.CellType = CellTypeExtensions.ChooseRandom();
		}

		public void DropPiece(Piece piece)
		{
			if (CheckCanDrop())
			{
				foreach (var point in piece.PiecePoints)
				{
					var pointInGrid = MousePosition.MoveBy(point);

					if (triGrid.Contains(pointInGrid))
					{
						triGrid[pointInGrid].CellType = CellType.Black;


						Destroy(piece);
						MakeNextPiece();
					}
				}
			}

		}

		private bool CheckCanDrop()
		{
			return true;
		}
	}
}