using System;
using DG.Tweening;
using UnityEngine;
using System.Collections;

namespace BingoBrain.Core
{
    public static class Jsvva
    {
        public static float NormalTimeScale = 1;

        public static void SetTimeScale(float timeScale)
        {
            Time.timeScale = timeScale;
            AppDispatcher.Instance.Dispatch(CsjInfoC.TimeScale_Change, timeScale);
        }

        public static float GetTimeScale()
        {
            return Time.timeScale;
        }

        public static float GetDeltaTime(bool isUnscale)
        {
            if (isUnscale)
            {
                return Time.unscaledDeltaTime;
            }
            else
            {
                return Time.deltaTime;
            }
        }

        public static Tweener SetUnscaledTime(Tweener tweener)
        {
            tweener.SetUpdate(true);
            return tweener;
        }

        public static Animator SetUnscaledTime(Animator animator)
        {
            animator.updateMode = AnimatorUpdateMode.UnscaledTime;
            return animator;
        }

        public static void SetParticleUnscaledTime(GameObject gameObject)
        {
            gameObject.AddComponent<Lucsah>();
        }

        public static IEnumerator PlayAnimation(Animation animation, string clipName, Action onComplete,
            bool isUnscaleTime)
        {
            if (!isUnscaleTime)
            {
                var currState = animation[clipName];
                var isPlaying = true;
                var progressTime = 0f;
                var timeAtLastFrame = 0f;
                var timeAtCurrentFrame = 0f;
                var deltaTime = 0f;
                animation.Play(clipName);
                timeAtLastFrame = Time.realtimeSinceStartup;

                while (isPlaying)
                {
                    timeAtCurrentFrame = Time.realtimeSinceStartup;
                    deltaTime = timeAtCurrentFrame - timeAtLastFrame;
                    timeAtLastFrame = timeAtCurrentFrame;

                    progressTime += deltaTime;
                    currState.normalizedTime = progressTime / currState.length;
                    animation.Sample();
                    if (progressTime >= currState.length)
                    {
                        if (currState.wrapMode != WrapMode.Loop)
                        {
                            isPlaying = false;
                        }
                        else
                        {
                            progressTime = 0.0f;
                        }
                    }

                    yield return new WaitForEndOfFrame();
                }

                yield return null;
                onComplete?.Invoke();
            }
            else
            {
                animation.Play(clipName);
            }
        }
    }
}