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

[Serializable]
public class TransformPath
{
	public string endNode;
	public Transform[] path;
	//Transform[] path;
}

public class BaseRoom : MonoBehaviour
{
	public bool useRoomStates = false;
	public Sprite[] roomStates;

	private List<Crew> CrewMembers = new List<Crew> ();
	public TransformPath[] path;

	public bool ContainsStairs = false;
	public int deckLevel;
	public int MaxHealth;

	[SerializeField]
	private int currentHealth;
	private bool critcalDamaged = false;

	protected GameController gameController;

	public bool IsRoomDamaged ()
	{
		return currentHealth != MaxHealth;
	}

	public bool IsRoomDestroyed ()
	{
		return critcalDamaged;
	}

	public int RoomHealth ()
	{
		return currentHealth;
	}

	public BaseRoom ReturnToRoom ()
	{
		return this;
	}

	public Transform[] this [string str] {
		get {
			for (int i = 0; i < path.Length; i++) {
				if (path [i].endNode == str)
					return path [i].path;
			}
			return null;
		}
	}
    
	// Use this for initialization
	void Awake ()
	{
		var gameControllerGO = GameObject.FindGameObjectWithTag ("GameController");
		if (gameControllerGO != null)
			gameController = gameControllerGO.GetComponent<GameController> ();

		currentHealth = MaxHealth;
	}

	void OnMouseDown ()
	{
		Debug.Log ("Clicked on " + gameObject.name + " room.");
		//Debug.logger("Key Down: " + Input.GetKey)
		if (!critcalDamaged) {
			if (Input.GetMouseButtonDown (0)) {
				if (gameController.SelectedCrew != null) {
					GetComponent<BaseRoom> ().AddCrew (gameController.SelectedCrew);
					gameController.SelectedCrew.MoveToRoom (this);
				}
			}
		}
	}

	void Update ()
	{
		if (useRoomStates) {
			if (currentHealth == MaxHealth) {
				this.GetComponent<SpriteRenderer> ().sprite = roomStates [0];
			} else if (currentHealth >= (MaxHealth / 2) && currentHealth < MaxHealth) {
				this.GetComponent<SpriteRenderer> ().sprite = roomStates [1];
			} else if (currentHealth < (MaxHealth / 2) && currentHealth > 0) {
				this.GetComponent<SpriteRenderer> ().sprite = roomStates [2];
			} else {
				this.GetComponent<SpriteRenderer> ().sprite = roomStates [3];
			}
		}
	}

	public void TakeDamage (int incomingDamage)
	{
		currentHealth -= incomingDamage;

		if (currentHealth <= 0) {
			critcalDamaged = true;
		}
	}

	public void GiveHealth (int healing)
	{
		currentHealth += healing;
	}

	public void AddCrew (Crew crew)
	{
		if (!CrewMembers.Contains (crew))
			CrewMembers.Add (crew);
	}

	public void RemoveCrew (Crew crew)
	{
		CrewMembers.Remove (crew);
	}
}
