using UnityEngine;
using System.Collections;
using Spine;
using Spine.Unity;

public class EyesSpawner : MonoBehaviour
{
    public GameObject eyesPrefab;
    public Transform targetPlayer;

    public bool isAnim;

    public string[] animations; 

    private GameObject m_eyesInstance;
    private SkeletonAnimation m_eyesSkeleton;

    public void Awake()
    {
        m_eyesInstance = Instantiate(eyesPrefab, new Vector3(500f, 0.5f, 500f), Quaternion.identity);
        m_eyesSkeleton = m_eyesInstance.GetComponentInChildren<SkeletonAnimation>();
    }

    private void Update()
    {
        if(targetPlayer == null)
        {
            CancelInvoke("ShowEyes");
            return;
        }

        if (isAnim)
        {
            Vector3 targetDir = m_eyesInstance.transform.position - targetPlayer.position;
            float angle = Vector3.Angle(targetDir, targetPlayer.forward);

            if (angle < 40f)
            {
                DisableAnim();
            }
        }
    }

    public void ShowEyes()
    {
        Vector3 pos = targetPlayer.position + targetPlayer.forward * Random.Range(-4f, -8f);
        pos.y = 0.3f;
        m_eyesInstance.transform.position = pos;
        m_eyesSkeleton.AnimationState.SetAnimation(0, animations[Random.Range(0, animations.Length)], false);
    }

    public void EnableAnim()
    {
        m_eyesInstance.SetActive(true);
        InvokeRepeating("ShowEyes", 1f, 3f);
        isAnim = true;
    }

    public void DisableAnim()
    {
        m_eyesInstance.SetActive(false);
        CancelInvoke("ShowEyes");
        isAnim = false;
    }
}
