using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameTile : MonoBehaviour {

	float BLINK_SLOW_COOLDOWN = .2f;
	float BLINK_FAST_COOLDOWN = .1f;
	float BLINK_COUNT = 15;
	float BLINK_FAST_START = 5;

	[Range(0,4)]
	public int row;

	[Range(0, 9)]
	public int col;

	[SerializeField]MeshRenderer _mesRenderer;

	[SerializeField]GameColor _gameColor;

	[SerializeField]Material[] _materialList;

	bool _changing;

	float _blinkTimer;
	float _blinkCount;

	public bool changing
	{
		get {return this._changing;}
	}


	public GameColor gameColor
	{
		get {return _gameColor;}
	}

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if (this._changing)
		{
			this._blinkTimer -= Time.deltaTime;

			if (this._blinkTimer < 0)
			{

				this._blinkCount--;
				if (this._blinkCount <= 0 )
				{
					RemoveFromValid();
					return;
				}
				else 
				{
					this._blinkTimer += (this._blinkCount < BLINK_FAST_START) ? BLINK_FAST_COOLDOWN : BLINK_SLOW_COOLDOWN;
				}


				SetGameColor((this._blinkCount % 2 == 0) ? this._gameColor : GameColor.None, false);
			}
		}
	}

	public void SetToRemove()
	{
		this._changing = true;
		this._blinkCount = BLINK_COUNT;

	}

	public void RemoveFromValid()
	{
		this._changing = false;
		SetGameColor(GameColor.None);

		GameManager.Instance.CheckTile(this);
	}

	public void SetGameColor(GameColor newColor, bool setIt = true)
	{
		Material newMaterial = this._materialList[0];
		switch (newColor)
		{
			case GameColor.Red:
				newMaterial = this._materialList[1];
				break;
			case GameColor.Blue:
				newMaterial = this._materialList[2];
				break;
			case GameColor.None:
			default:
				newMaterial = this._materialList[0];
				break;

		}
	

		this._mesRenderer.materials = new Material[]{newMaterial, this._mesRenderer.materials[1]};
		if (setIt) this._gameColor = newColor;
	}

	public void StopChanging()
	{
		this._changing = false;
		SetGameColor(this._gameColor, false);
	}
}
