using UnityEngine;
using System.Collections;

public class ButtonCollider : MonoBehaviour {
	const float SCREEN_RAY_LENGTH = 20f;
	
	public delegate void Action();
	
	Action action;
	
	BoxCollider buttonCollider;
	public Vector3 size = Vector3.one;
	int touchId = -1;

	public void AddReceiver(Action newAction) {//action
		action = newAction;
	} 

	public static ButtonCollider AddToObject(GameObject buttonObject, Vector3 size , Action action = null) {//action
		ButtonCollider buttonCollide = buttonObject.AddComponent<ButtonCollider>();
		buttonCollide.size = size;
		buttonCollide.action = action;
		return buttonCollide;
	}

	public static ButtonCollider AddToObject(GameObject buttonObject, float size = 1f , Action action = null) {//action
		return AddToObject(buttonObject, Vector3.one * size, action);
	} 
	
	void Start () {
		buttonCollider = GetComponent<BoxCollider>();
		if (buttonCollider == null) {
			buttonCollider = gameObject.AddComponent<BoxCollider>();		
		}
		buttonCollider.size = size;
	}
	
	void Update () {
		for(int i = 0; i < Input.touches.Length; i++) {
			if (Input.touches[i].phase == TouchPhase.Began) {
				RaycastHit info;
				if (buttonCollider.Raycast(MainCamera.mainCamera.ScreenPointToRay(Input.touches[i].position), out info, SCREEN_RAY_LENGTH)){
					touchId = Input.touches[i].fingerId;
					break;
				}
			}
			if (Input.touches[i].phase == TouchPhase.Ended || Input.touches[i].phase == TouchPhase.Canceled) {
				RaycastHit info;
				if (buttonCollider.Raycast(MainCamera.mainCamera.ScreenPointToRay(Input.touches[i].position), out info, SCREEN_RAY_LENGTH)){
					if (touchId == Input.touches[i].fingerId) {
						if (action != null){
							action();
						}
					}
					touchId = -1;
					break;
				}
			}
		}
		if (Input.GetMouseButtonUp(0)) {
			RaycastHit info;
			if (buttonCollider.Raycast(MainCamera.mainCamera.ScreenPointToRay(Input.mousePosition), out info, SCREEN_RAY_LENGTH)){
				if (action != null){
					action();
				}
			}
		}
	}
}
