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

public class TipsInfoController : MonoBehaviour {

    float lastClickShowTime;
    
    // Use this for initialization
    void Start () {
		
	}

    TipsInfo m_CurInfo;
    string toAvoidDestroy = "";//避免点同样位置的icon重复生成TipsInfo
    public void ShowTipsInfo(string content,Transform parent,Vector2 anchoredPos)
    {
        GameDebug.Log("ShowTipsInfo:"+content);
        toAvoidDestroy = content;

        if (m_CurInfo &&
          toAvoidDestroy != m_CurInfo.content)
        {
            Destroy(m_CurInfo.gameObject);
            m_CurInfo = null;
        }

        if (!m_CurInfo)
        {
            var pref = GameResourceManager.Load<TipsInfo>(GameResourceManager.tipsInfo);
            m_CurInfo = Instantiate<TipsInfo>(pref, parent);
            m_CurInfo.Init(content);
            m_CurInfo.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(anchoredPos.x, anchoredPos.y, 0);
            m_CurInfo.Show(()=>
            {
                toAvoidDestroy = "";
            }
            );
        }
        lastClickShowTime = Time.time;
    }

    /// <summary>
    /// 点击其他地方删除TipsInfo，点击同一个地方则不删除
    /// </summary>
    /// <returns></returns>
    IEnumerator DelayClearObjs()
    {
        yield return new WaitForSeconds(0.1f);

        if ((Time.time - lastClickShowTime) < 0.3f)
        {
            yield break;
        }

        if (string.IsNullOrEmpty(toAvoidDestroy)||
        !toAvoidDestroy .Equals(m_CurInfo.content)
        )
        {
            if (m_CurInfo)
            {
                GameDebug.Log("toAvoidDestroy:" + toAvoidDestroy + "   m_CurInfo.content:" + m_CurInfo.content);

                m_CurInfo.Hide(() =>
                {
                    Destroy(m_CurInfo.gameObject);
                    m_CurInfo = null;
                });
            }
        }
        toAvoidDestroy = "";
    }
    
    
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if(gameObject.activeInHierarchy)
                StartCoroutine(DelayClearObjs());
        }
        
    }
}
