using UnityEngine;
using System.Collections;

// If dragging cup, the index will be returned of the initial cup, as well as release?
public enum TouchState { Start, Stay, End }
public delegate void ScreenTouch(Vector2 position, TouchState state);

public class InputManager : Singleton<InputManager>
{
    private bool touchEnabled = false;
    private Vector2 touchPosition;
    private ScreenTouch delegateScreenTouch;

    void Update()
    {
        if (touchEnabled)
            CheckTouch();
    }

    private void CheckTouch()
    {
        if (delegateScreenTouch == null)
            return;

        bool touch = false;
        TouchState state = TouchState.Stay;

        if (Input.GetMouseButton(0))
        {
            touchPosition = Input.mousePosition;
            touch = true;
            if (Input.GetMouseButtonDown(0))
                state = TouchState.Start;
        }

        if (Input.GetMouseButtonUp(0))
        {
            state = TouchState.End;
            touch = true;
        }

        if (Input.touchCount == 1)
        {
            touchPosition = Input.GetTouch(0).position;
            touch = true;
            if (Input.GetTouch(0).phase == TouchPhase.Began)
                state = TouchState.Start;
            if (Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled)
                state = TouchState.End;
        }

        if (touch)
        {
            delegateScreenTouch(touchPosition, state);
        }
    }

    public bool IsScreenTouched()
    {
        return (Input.GetMouseButton(0) || Input.touchCount > 0);
    }

    public void SetDetectTouch(bool enabled)
    {
        touchEnabled = enabled;
    }

    // Quite unnecessary methods :D
    public void AddTouchListener(ScreenTouch del)
    {
        delegateScreenTouch += del;
    }

    public void RemoveTouchListener(ScreenTouch del)
    {
        delegateScreenTouch -= del;
    }
}
