using FL.Battle.Buffs;
using System.Collections.Generic;
using UnityEngine;
using XGame.Framework.Map;

namespace FL.Map.UI
{
    /// <summary>
    /// TODO 临时代码
    /// </summary>
    internal class BattleInfoBuffList : MonoBehaviour
    {
        [SerializeField]
        private BattleInfoBuffListItem _template;
        [SerializeField]
        private int _itemLimit = 4;
        private BattleInfoBuffListItem[] _items;

        private void Awake()
        {
            _items = new BattleInfoBuffListItem[_itemLimit];
        }
        private void OnDisable()
        {
            foreach (var item in _items)
            {
                if (item == null)
                    break;
                item.gameObject.SetActive(false);
            }
        }
        public void Refresh(List<IBuff> buffs, MapContext context)
        {
            var showCount = Mathf.Clamp(buffs.Count, 0, _itemLimit);
            for (var i = 0; i < _itemLimit; i++)
            {
                var item = _items[i];
                if (i < showCount)
                { // 需要显示
                    var buff = buffs[i];
                    if (item == null)
                    {
                        item = GameObject.Instantiate<BattleInfoBuffListItem>(_template, _template.transform.parent);
                        _items[i] = item;
                    }
                    var loadAsync = context.Asset.LoadAsync<Sprite>(buff.IconName);
                    loadAsync.On(_ =>
                    {
                        item.buffIcon.sprite = loadAsync.Result;
                    });
                    var layers = buff.Layers;
                    item.buffNumTxt.text = layers > 1 ? layers.ToString() : string.Empty;
                    item.gameObject.SetActive(true);
                }
                else
                { // 隐藏
                    if (item == null)
                    {
                        break;
                    }
                    item.gameObject.SetActive(false);
                }
            }
        }
    }
}
