using UnityEngine;
using System.Collections;

public class PlayerInteraction : MonoBehaviour
{
    public GameObject spawnPoint;
    public GameObject interactionUI;

    private IInteractable _interactable;

    private bool _hold;

    private void Start()
    {
        Respawn();
    }

    public void Respawn()
    {
        _hold = false;
        _interactable = null;
        if (interactionUI)
            interactionUI.SetActive(false);
        transform.position = spawnPoint.transform.position;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E) && _interactable != null)
        {
            if (_interactable.IsHandheld && !_hold)
                _hold = true;
            else if (_interactable.IsHandheld && _hold)
                _hold = false;

            _interactable.Interact(gameObject);
        }

        if (Input.GetKeyDown(KeyCode.T))
        {
            LevelManager.Instance.Reset();
            Application.LoadLevel(Application.loadedLevel);
        }

        if (Input.GetKeyDown(KeyCode.Escape))
            Application.Quit();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (_hold)
            return;

        _interactable = (IInteractable)other.gameObject.GetComponent(typeof(IInteractable));

        if (interactionUI)
        {
            if (_interactable != null && _interactable.IsActivatableOnKey)
                interactionUI.SetActive(true);
            else
                interactionUI.SetActive(false);
        }            
    }

    private void OnTriggerExit(Collider other)
    {
        if (_hold)
            return;

        if (interactionUI)
            interactionUI.SetActive(false);

        _interactable = null;
    }
}
