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

public class InputScreen : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private Vector2 fingerDown;
    private Vector2 fingerUp;

    public float SWIPE_THRESHOLD = 20f;

    public delegate void OnSwipeInputDelegate(string directionName);
    public static event OnSwipeInputDelegate swipeInputDelegate = null;

    public delegate void OnTapInputDelegate(string sideName);
    public static event OnTapInputDelegate tapInputDelegate = null;

    public void OnPointerUp(PointerEventData pointerEventData)
    {
        fingerDown = pointerEventData.position;
        checkSwipe();
    }

    public void OnPointerDown(PointerEventData pointerEventData)
    {
        fingerUp = pointerEventData.position;
        fingerDown = pointerEventData.position;
    }

    void checkSwipe()
    {
        //Check for Vertical swipe
        if (verticalDelta() > SWIPE_THRESHOLD && verticalDelta() > horizontalDelta())
        {
            if (fingerDown.y - fingerUp.y > 0)
            {
                OnSwipe("Up");
            }
            else if (fingerDown.y - fingerUp.y < 0)
            {
                OnSwipe("Down");
            }
            fingerUp = fingerDown;
        }
        //Check for Horizontal swipe
        else if (horizontalDelta() > SWIPE_THRESHOLD && horizontalDelta() > verticalDelta())
        {
            if (fingerDown.x - fingerUp.x > 0)
            {
                OnSwipe("Right");
            }
            else if (fingerDown.x - fingerUp.x < 0)
            {
                OnSwipe("Left");
            }
            fingerUp = fingerDown;
        }
        //Tap Input
        else if (fingerUp.x > (Screen.width / 2))
        {
            tapInput("Right");
        }
        else if (fingerUp.x < (Screen.width / 2))
        {
            tapInput("Left");
        }
        else
            throw new System.Exception("Unidentified Input!");
    }

    float verticalDelta()
    {
        return Mathf.Abs(fingerDown.y - fingerUp.y);
    }

    float horizontalDelta()
    {
        return Mathf.Abs(fingerDown.x - fingerUp.x);
    }

    private void tapInput(string sideName)
    {
        Debug.Log("Tap " + sideName);

        tapInputDelegate(sideName);
    }

    private void OnSwipe(string directionName)
    {
        Debug.Log("Swipe " + directionName);

        swipeInputDelegate(directionName);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
            OnSwipe("Up");
        if (Input.GetKeyDown(KeyCode.A))
            OnSwipe("Left");
        if (Input.GetKeyDown(KeyCode.S))
            OnSwipe("Down");
        if (Input.GetKeyDown(KeyCode.D))
            OnSwipe("Right");
    }
}