using UnityEngine;
using System.Collections;

public class Teleporter : MonoBehaviour, IInteractable
{
    public int id;
    public int targetId;

    public float cooldown;

    public bool activateOnTriggerEnter;

    public float CooldownProgress { get { return _remainingCooldown / cooldown; } }

    private void Awake()
    {
        _remainingCooldown = 0f;
        _triggerAfterCooldown = false;
        LevelManager.Instance.RegisterTeleporter(this);
    }

    public void LinkTo(Teleporter teleporter)
    {
        _targetTeleporter = teleporter;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (!activateOnTriggerEnter)
            return;

        if (other.tag == "Player")
            SimulateInteract(other.gameObject);
    }

    private void OnTriggerExit(Collider other)
    {
        _triggerAfterCooldown = false;
    }

    public bool Interact(object sender)
    {
        if (_targetTeleporter == null || activateOnTriggerEnter)
            return false;

        if (_remainingCooldown > 0f)
            StartCoroutine(TriggerAfterCooldown(sender as GameObject));
        else
            TeleportObject(sender as GameObject);

        return true;
    }

    private bool SimulateInteract(object sender)
    {
        if (_targetTeleporter == null)
            return false;

        if (_remainingCooldown > 0f)
            StartCoroutine(TriggerAfterCooldown(sender as GameObject));
        else
            TeleportObject(sender as GameObject);

        return true;
    }

    private void TeleportObject(GameObject obj)
    {
        ObjectTeleported();
        _targetTeleporter.ObjectTeleported();

        obj.SetActive(false);
        obj.transform.position = _targetTeleporter.transform.position;
        obj.SetActive(true);
    }

    private void ObjectTeleported()
    {
        StartCoroutine(StartCooldown());
    }

    private IEnumerator StartCooldown()
    {
        _remainingCooldown = cooldown;

        while (_remainingCooldown > 0f)
        {
            yield return null;
            _remainingCooldown -= Time.deltaTime;
        }
    }

    private IEnumerator TriggerAfterCooldown(GameObject sender)
    {
        while (_remainingCooldown > 0f)
            yield return null;

        if (_triggerAfterCooldown)
            TeleportObject(sender);
    }

    public bool IsActivatableOnKey
    {
        get { return !activateOnTriggerEnter; }
    }

    private Teleporter _targetTeleporter;
    private float _remainingCooldown;
    private bool _triggerAfterCooldown;


    public bool IsHandheld
    {
        get { return false; }
    }
}
