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

public class BlockGrid: GridBehaviour<RectPoint>
{
	private RectGrid<IBlockCell> foregroundGrid;

	public List<GameObject> prefabs;

	private int currentPrefabIndex = 0;

	public override void InitGrid()
	{
		foregroundGrid = (RectGrid<IBlockCell>) Grid.CloneStructure<IBlockCell>();

		foreach (var point in foregroundGrid)
		{
			foregroundGrid[point] = null;
		}
	}

	public void Update()
	{
		if (Input.GetKeyDown(KeyCode.Alpha0))
		{
			currentPrefabIndex = 0;
		}
		if (Input.GetKeyDown(KeyCode.Alpha1))
		{
			currentPrefabIndex = 1;
		}
		if (Input.GetKeyDown(KeyCode.Alpha2))
		{
			currentPrefabIndex = 2;
		}
		if (Input.GetKeyDown(KeyCode.Alpha3))
		{
			currentPrefabIndex = 3;
		}
	}

	public void OnClick(RectPoint point)
	{
		var prefab = (IBlockCell) prefabs[currentPrefabIndex].GetComponent(typeof(IBlockCell));
		var cover = prefab.GetCover(point);

		if (cover.All(foregroundGrid.Contains))
		{
			var cell = (IBlockCell) Instantiate(prefab.gameObject).GetComponent(typeof(IBlockCell));
			cell.ResetPosition();

			cell.transform.parent = transform;
			cell.transform.localScale = Vector3.one;
			cell.transform.localPosition = Map[point];

			foreach (var coverPoint in cover)
			{
				if (foregroundGrid[coverPoint] != null)
				{
					KillCellAt(coverPoint);
				}

				foregroundGrid[coverPoint] = cell;
			}
		}
	}

	private void KillCellAt(RectPoint point)
	{
		Debug.Log("Cell Killed!");

		var cell = foregroundGrid[point];

		var cover = cell.GetCover(point);

		foreach (var coverPoint in cover)
		{
			foregroundGrid[coverPoint] = null;
		}

		Destroy(cell.gameObject);
	}
}
