using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Collider2D))]
public class Dialogger : MonoBehaviour {

    public Canvas DialogCanvas;
    public string message;
    public bool isTriggered = false;

    private Collider2D collider;
    private Agent agent;
    private SpriteRenderer spriteRenderer;

	// Use this for initialization
	void Awake () {
        DialogCanvas = GameObject.Find("DialogBox").GetComponent<Canvas>();
        collider = GetComponent<Collider2D>();

        agent = transform.parent.GetComponent<Agent>();
        spriteRenderer = GetComponent<SpriteRenderer>();
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyUp(KeyCode.H))
        {
            if (isTriggered) // && !DialogCanvas.activeInHierarchy)
            {
                DialogCanvas.GetComponentInChildren<Text>().text = message;
                DialogCanvas.transform.position = collider.bounds.center + collider.bounds.extents * 0.5f + 
                    new Vector3(DialogCanvas.GetComponent<RectTransform>().rect.width, DialogCanvas.GetComponent<RectTransform>().rect.height, 0) * 0.5f;
                DialogCanvas.gameObject.SetActive(true);
                agent.SetState(AgentState.Idle);
            }
            //else
            //{
            //    DialogCanvas.SetActive(false);
            //}
        }

	}

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (!collision.tag.Equals("Player")) return;


        isTriggered = true;
        spriteRenderer.enabled = true;
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (!collision.tag.Equals("Player")) return;

        isTriggered = false;
        DialogCanvas.gameObject.SetActive(false);
        agent.SetState(agent.prevState);
        spriteRenderer.enabled = false;
    }
}
