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

public class HUDBase : MonoBehaviour
{
    public Action<HUDBase> DelDestroy;

    public bool HasTarget => mTargetTrans != null;
    public Transform TargetTrans => mTargetTrans;

    protected RectTransform mRectTrans = null;

    protected Transform mTargetTrans = null;
    protected Canvas mRootCanvas = null;
    protected Camera mCamera = null;
    protected float mHOffset;
    protected bool mIsActive = false;

    private void Awake()
    {
        mRectTrans = GetComponent<RectTransform>();
        if (mRectTrans == null)
        {
            Debug.LogError("RectTransform is invalid.");
            return;
        }

        OnAwake();
    }

    public void Init(Transform pTargetTrans, Canvas pRootCanvas, Camera pCamera, float pHOffset)
    {
        if (pTargetTrans == null)
        {
            Debug.LogError("Target is invalid.");
            return;
        }

        mTargetTrans = pTargetTrans;
        mRootCanvas = pRootCanvas;
        mCamera = pCamera;
        mHOffset = pHOffset;
        mIsActive = true;

        Refresh();

        OnInit();
    }

    public void Refresh()
    {
        if (!HasTarget || mCamera == null)
            return;

        Vector3 worldPosition = mTargetTrans.position + Vector3.up * mHOffset;
        Vector3 screenPosition = mCamera.WorldToScreenPoint(worldPosition);

        Vector2 position;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)mRootCanvas.transform, screenPosition, mRootCanvas.worldCamera, out position))
        {
            mRectTrans.localPosition = position;
        }
    }

    public void RefreshHeight(float pHeight)
    {
        mHOffset = pHeight;
        Refresh();
    }

    public void Destroy()
    {
        if (!mIsActive)
            return;

        mIsActive = false;

        ResetTarget(null);
        OnDestroy();

        DelDestroy?.Invoke(this);
        DelDestroy = null;
    }

    public virtual void ResetTarget(Transform pTargetTrans)
    {
        mTargetTrans = pTargetTrans;
    }

    protected virtual void OnAwake()
    {

    }

    protected virtual void OnInit()
    {

    }

    protected virtual void OnDestroy()
    {

    }
}