using TMPro;
using UnityEngine;

namespace TyphoonUnitySDK
{
    public class Toast : MonoSingleton<Toast>
    {
        private static float RADIAN_90 = 90 * Mathf.Deg2Rad;

        /*出现动画的时长*/
        private const float APPEAR_DURAITON = 0.25F;
        private const float HIDE_DURAITON = 0.25F;
        public CanvasGroup View;
        public TextMeshProUGUI TxtContent;
        public GameObject Canvas;

        public bool IsPlaying = false;
        public float PlayingTime = 0;
        public float Duration = 2;
        public float HideStartTime;

        protected override void Init()
        {
            base.Init();
            DontDestroyOnLoad(gameObject);
            var source = Resources.Load<GameObject>("TYPHOON_SDK_TOAST_CANVAS");
            Canvas = GameObject.Instantiate(source, null);
            DontDestroyOnLoad(Canvas);
            View = Canvas.GetComponentInChildren<CanvasGroup>();
            TxtContent = Canvas.GetComponentInChildren<TextMeshProUGUI>();
        }

        public void Show(string content, float duration = 1.6f)
        {
            View.alpha = 0;
            TxtContent.text = content;
            View.transform.localScale = Vector3.zero;
            IsPlaying = true;
            PlayingTime = 0;
            Duration = Mathf.Clamp(duration, 0.5f, float.MaxValue);
            HideStartTime = Duration - HIDE_DURAITON;
        }

        private void Update()
        {
            if (IsPlaying)
            {
                PlayingTime += Time.unscaledDeltaTime;
                if (PlayingTime < APPEAR_DURAITON)
                {
                    var process = PlayingTime / APPEAR_DURAITON;
                    var scale = Mathf.Sin(Mathf.Lerp(0, RADIAN_90, process));
                    View.transform.localScale = new Vector3(scale, scale, 1);
                    View.alpha = scale;
                }
                else if (PlayingTime > HideStartTime)
                {
                    var process = (PlayingTime - HideStartTime) / HIDE_DURAITON;
                    var alpha = Mathf.Lerp(1, 0, process);
                    View.alpha = alpha;
                }
                else
                {
                    View.transform.localScale = Vector3.one;
                    View.alpha = 1;
                }

                if (PlayingTime > Duration)
                {
                    IsPlaying = false;
                    View.alpha = 0;
                }
            }
        }

        public void Clear()
        {
            IsPlaying = false;
            View.alpha = 0;
        }
    }
}