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

public class TheHill : MonoBehaviour {

	bool hasAKing;
	PlayerNames kingsTeam;
	List<PlayerController> playersOnHill;
	PlayerController king;

	public int score = 2;

	void Start () {
		hasAKing = false;
		StartCoroutine (TheKingOfTheHill());
		playersOnHill = new List<PlayerController> ();
	}

	void Update() {
		Debug.Log (hasAKing);
	}

	void OnCollisionEnter2D (Collision2D coll) {
		if (coll.gameObject.CompareTag ("Player")) {
			PlayerController p = coll.gameObject.GetComponent<PlayerController> ();

			Debug.Log (p.GetType().Name);
			playersOnHill.Add(p);
			if (!hasAKing) {
				kingsTeam = playersOnHill[playersOnHill.Count-1].playerName;
				king = playersOnHill [playersOnHill.Count - 1];
			}
		}
	}

	void OnCollisionExit2D (Collision2D coll) {
		if (coll.gameObject.CompareTag ("Player")) {
			PlayerController p = coll.gameObject.GetComponent<PlayerController> ();
			playersOnHill.Remove (p);

			if (p.playerName == kingsTeam) {
				kingsTeam = PlayerNames.NENHUM;
				king = null;
				bool sameKingTeam = false;
				for (int i = 0; i < playersOnHill.Count; i++) {
					if (playersOnHill [i].playerName == kingsTeam) {
						sameKingTeam = true;
						kingsTeam = playersOnHill [i].playerName;
						king = playersOnHill [i];
					}
				}
				if (!sameKingTeam && playersOnHill.Count > 0) {
					king = playersOnHill [0];
					kingsTeam = king.playerName;
				}
			}

		}
	}//end on collision exit

	IEnumerator TheKingOfTheHill () {
		while (true) {
			yield return new WaitForSeconds (1f);
			if (king != null && GameController.GetCurrentStates() == GameStates.GAME_PLAY) {
				king.AddScore (score);
			}
		}
	}
}
