using UnityEngine;
using System.Collections;

public class Interact : MonoBehaviour {

    public delegate void UseSpinnerStart();
    public static event UseSpinnerStart OnUseStart;

    public delegate void UseSpinnerStop();
    public static event UseSpinnerStop OnUseStop;

    public delegate void UseSpinnerFinish();
    public static event UseSpinnerFinish OnUseFinish;

    public delegate void ActivateSpinner(Transform targetTransform, float countdownTime);
    public static event ActivateSpinner OnSpinnerActivate;

    public delegate void DeactivateSpinner();
    public static event DeactivateSpinner OnSpinnerDeactivate;

    public bool canInteract = true;
    public float useCountdownTime = 1.5f;

    protected IEnumerator useCoroutine;

    // Use this for initialization
    protected virtual void Start () {
	    
	}
	
	// Update is called once per frame
	void Update () {
        if (canInteract)
        {
            if (Input.GetButtonDown("Interact"))
            {
                useCoroutine = UseCountdown();
                StartCoroutine(useCoroutine);

            }
            if (Input.GetButtonUp("Interact"))
            {
                if(OnUseStop != null)
                {
                    OnUseStop();
                }
                if(useCoroutine != null)
                {
                    StopCoroutine(useCoroutine);
                }
            }
        }
	}

    /**
    USE
    Will be inherited and changed by children.
    Used to trigger their unique events when use is called
    **/
    protected virtual void Use()
    {

    }

    /**
    USE COUNTDOWN
    The confirmation countdown. Calls Use() at end. Can be cancelled if user stops confirming
    **/
    IEnumerator UseCountdown()
    {
        if(OnUseStart != null)
        {
            OnUseStart();
        }
        yield return new WaitForSeconds(useCountdownTime);
        if(OnUseFinish != null)
        {
            OnUseFinish();
        }
        Use();
    }

    protected virtual void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            canInteract = true;
            if(OnSpinnerActivate != null)
            {
                OnSpinnerActivate(transform, useCountdownTime);
            }
        }
    }

    protected void ActivateSpinnerEvent()
    {
        if (OnSpinnerActivate != null)
        {
            OnSpinnerActivate(transform, useCountdownTime);
        }
    }

    protected virtual void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            canInteract = false;
            if (useCoroutine != null)
            {
                StopCoroutine(useCoroutine);
            }
            if (OnSpinnerDeactivate != null)
            {
                OnSpinnerDeactivate();
            }
        }
    }
}
