using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Utils;

namespace Base
{
    public interface ITick
    {
        public void Tick()
        {
        }
    }

    public interface ITickPhysics
    {
        public void TickPhysics()
        {
        }
    }

    public interface ITickUI
    {
        public void TickUI()
        {
        }
    }

    public class Clock : MonoSingleton<Clock>
    {
        private bool _pause = false;
        public bool Pause
        {
            get
            {
                return _pause;
            }
            set
            {
                if (value)
                {
                    Time.timeScale = 0;
                }
                else
                {
                    Time.timeScale = 1;
                }
                _pause = value;
            }
        }
        public List<ITickPhysics> tickPhysics = new();
        public List<ITick> ticks = new();
        public List<ITickUI> tickUIs = new();

        private void Update()
        {
            if (!_pause)
                foreach (var tick in ticks)
                    tick.Tick();

            foreach (var uiTick in tickUIs) uiTick.TickUI();
            //if (timer > 1)
            //{
            //    timer -= 1;
            //    Debug.Log("滴答");
            //}
            //timer += Time.deltaTime;
        }

        private void FixedUpdate()
        {
            if (!_pause)
                foreach (var physicsTick in tickPhysics)
                    physicsTick.TickPhysics();
        }

        private void OnDestroy()
        {
            // 移除事件监听
            SceneManager.sceneLoaded -= OnSceneLoaded;
        }

        protected override void OnStart()
        {
            // 注册场景加载事件
            SceneManager.sceneLoaded += OnSceneLoaded;

            // 初始化时调用一次
            Init();
        }

        private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            // 场景加载完成后调用 Init 方法
            Init();
        }

        /// <summary>
        ///     初始化方法
        /// </summary>
        public void Init()
        {
            ticks.Clear();
            tickPhysics.Clear();
            tickUIs.Clear();

            foreach (var obj in FindObjectsByType<MonoBehaviour>(FindObjectsSortMode.None))
            {
                if (obj is ITick tickObj) ticks.Add(tickObj);
                if (obj is ITickPhysics physicsObj) tickPhysics.Add(physicsObj);
                if (obj is ITickUI uiObj) tickUIs.Add(uiObj);
            }
        }
    }
}