using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// UI帧动画管理器 - 负责帧动画资源的加载和管理
/// 
public class UIFrameMgr {
    private static UIFrameMgr _inst = null;
    private static readonly object _lock = new object();
    
    public static UIFrameMgr Inst {
        get {
            if (_inst == null) {
                lock (_lock) {
                    if (_inst == null) {
                        _inst = new UIFrameMgr();
                    }
                }
            }
            return _inst;
        }
    }
    // 帧动画资源缓存
    private Dictionary> allFrameDic = new Dictionary>();
    // 是否已初始化
    private bool isInitialized = false;
    public UIFrameMgr()
    {
        Init();
    }
    /// 
    /// 初始化管理器
    /// 
    public void Init()
    {
        if (isInitialized)
            return;
            
        allFrameDic.Clear();
        isInitialized = true;
    }
    /// 
    /// 加载指定帧动画资源
    /// 
    private void LoadFrameSprites(FrameAnimationConfig cfg)
    {
        if (allFrameDic.ContainsKey(cfg.name))
            return;
            
        List spriteList = new List();
        
        for (int i = 1; i <= cfg.frameCnt; i++)
        {
            string spritePath = "Sprite/" + cfg.folder;
            string spriteName = StringUtility.Contact(cfg.name, "_", i);
            
            Sprite sprite = ResManager.Instance.LoadAsset(spritePath, spriteName);
            if (sprite != null)
            {
                spriteList.Add(sprite);
            }
        }
        
        if (spriteList.Count > 0)
        {
            allFrameDic.Add(cfg.name, spriteList);
        }
    }
    /// 
    /// 获取帧动画资源
    /// 
    public List GetDynamicImage(string key)
    {
        // 按需加载资源
        if (!allFrameDic.ContainsKey(key))
        {
            LoadFrameSprites(FrameAnimationConfig.Get(key));
        }
        
        if (allFrameDic.TryGetValue(key, out var list))
        {
            return list;
        }
        return null;
    }
    /// 
    /// 检查是否包含指定帧动画
    /// 
    public bool ContainsDynamicImage(string key)
    {
        return FrameAnimationConfig.HasKey(key);
    }
    
    
    /// 
    /// 预加载指定帧动画
    /// 
    public void PreloadDynamicImage(string key)
    {
        if (!allFrameDic.ContainsKey(key))
        {
            LoadFrameSprites(FrameAnimationConfig.Get(key));
        }
    }
}