using UnityEngine;
using System.Collections;

public class Button : MonoBehaviour {
	
	public delegate void Receiver();
	public delegate void TagReceiver(int tag);
	
	public Sprite activeSprite;
	public Sprite backSprite;
	
	BoxCollider mainCollider;
	
	bool visibility = true;
	public bool hover = false;
	
	Receiver Action = null;
	TagReceiver ActionWithTag = null;
	int actionTag;
	
	Vector3 size 	= Vector3.one;
	Vector3 center	= Vector3.zero;
	
	public bool visible{
        get{
            return visibility;
        }
        set{
			SetVisible(value);
		}
    }
	
	private void SetVisible(bool val){
		if(visibility != val){
			visibility = val;
			if (activeSprite != null){
				activeSprite.visible = val;
			}
			if (backSprite != null){
				backSprite.visible = val;
			}
		}
	}
	
	public void SetSize(Vector3 buttonSize){
		size = buttonSize;
		if (mainCollider != null) {
			size = buttonSize;
		}
	}
	public void SetCenter(Vector3 buttonCenter){
		center = buttonCenter;
		if (mainCollider != null) {
			center = buttonCenter;
		}
	}
	
	public void SetSprite( Sprite active, Sprite back){
		activeSprite = active;
		backSprite   = back;
		back.visible = false;
	}
	
	public void SetReceiver( Receiver action){
		Action = action;
	}
	
	public void SetReceiverWithTag( TagReceiver action, int tag){
		ActionWithTag = action;
		actionTag = tag;
	}
	
	void Awake (){
		mainCollider = gameObject.GetComponent<BoxCollider>();
		if (mainCollider == null) {
			mainCollider = gameObject.AddComponent<BoxCollider>();
		}
	}
	
	void Start () {
		mainCollider.size   = size;
		mainCollider.center = center;
	}
	
	void Update(){
		if (visibility)	{
			if ((Control.touches[0].state == TouchState.Begin) || (Control.touches[0].state == TouchState.Touch)) {
				Ray ray = PerPixelCamera.mainCamera.ScreenPointToRay(Control.touches[0].screenPosition);
				RaycastHit hit;
				if (mainCollider.Raycast(ray, out hit, 100)){
					hover = true;
					if (activeSprite != null) {
						activeSprite.visible = false; 
					}
					if (backSprite != null) {
						backSprite.visible   = true;
					}
				}
			}
			else {
				if (hover){
					hover = false;
					if (backSprite != null) {
						backSprite.visible   = false;
					}
					if (activeSprite != null) {
						activeSprite.visible = true;
					}
					if (Control.touches[0].state == TouchState.End){
						if (Action != null)
							Action();
						if (ActionWithTag != null)
							ActionWithTag(actionTag);
					}
				}
			}
		}
	}
}
