using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

public class BuildingPlacer : MonoBehaviour {

	bool canPlace = false;

	// Use this for initialization
	void Start () {
		UpdateRangeCircle();
		GameObject.Find ("ESC to Cancel Building").GetComponent<CanvasGroup>().alpha = 1;
	}

	void UpdateRangeCircle() {
		Booster b = GetComponent<Booster>();
		if(b != null) {
			RangeCircle.LockTo(transform, b.CurrentRadius(), true);
		}
		
		Soulzooka s = GetComponent<Soulzooka>();
		if(s != null) {
			RangeCircle.LockTo(transform, s.radius, true);
		}
		
		Turret t = GetComponent<Turret>();
		if(t != null) {
			RangeCircle.LockTo(transform, t.CurrentRange(), false);
		}

	}

	void OnDestroy() {
		GameObject.Find ("ESC to Cancel Building").GetComponent<CanvasGroup>().alpha = 0;

	}

	// Update is called once per frame
	void Update () {
		UpdateRangeCircle();
		canPlace = false;

		//Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );

		Vector3 mousePos = Camera.main.ScreenToWorldPoint( Input.mousePosition );
		mousePos.z = 0;
		this.transform.position = mousePos;

		Collider2D col = GetComponent<Collider2D>();

		if(GetComponent<Turret>() != null) {
			GetComponent<Turret>().UpdateBoosts();
		}


		if( Game.current.CanAffordCurrentBuilding() && 
		   !col.IsTouchingLayers( LayerMask.GetMask("NotBuildable") ) && 
		   !col.IsTouchingLayers( LayerMask.GetMask("Building") ) 
		   ) {
			SpriteRenderer[] srs = GetComponentsInChildren<SpriteRenderer>();
			foreach(SpriteRenderer sr in srs)
				sr .color = Color.green;

			canPlace = true;
		}
		else {
			SpriteRenderer[] srs = GetComponentsInChildren<SpriteRenderer>();
			foreach(SpriteRenderer sr in srs)
				sr .color = Color.red;
		}

		if( EventSystem.current.IsPointerOverGameObject() != true && canPlace && Input.GetMouseButtonDown(0) ) {
			Debug.Log ("Placing building: " + gameObject.name);

			SpriteRenderer[] srs = GetComponentsInChildren<SpriteRenderer>();
			foreach(SpriteRenderer sr in srs)
				sr .color = Color.white;

			if(GetComponent<SoulChamber>() != null)
				GetComponent<SoulChamber>().enabled = true;
			if(GetComponent<Turret>() != null)
				GetComponent<Turret>().enabled = true;
			if(GetComponent<Booster>() != null)
				GetComponent<Booster>().enabled = true;

			RangeCircle.TurnOff();

			SoundManager.current.PlaySound("Building Place");

			Destroy( GetComponent<Rigidbody2D>() );
			Destroy( this );
			Game.current.BuildingWasPlaced();
		}
	}
}
