using System;
using UnityEngine;
using UnityEngine.UI;

namespace Guru.UI
{

    /// <summary>
    /// 评分星星条
    /// </summary>
    public class UIRatingStars : MonoBehaviour
    {

        [SerializeField] private HorizontalLayoutGroup _layout;
        private UIRatingStarItem[] _stars;

        private int _value;

        public int Value
        {
            get => _value;
            set => SetValue(value);
        }

        private bool _isRtl = false;
        public bool IsRTL
        {
            get => _isRtl;
            set => SetIsRTL(value);
        }

        private bool _enabled = false;

        public bool Enabled
        {
            get => _enabled;
            set => _enabled = value;
        }


        public Action<int> OnValueChanged;

        #region 初始化

        private void Awake()
        {
            Enabled = true;
            InitStars();
        }

        /// <summary>
        /// 设置星星数量
        /// </summary>
        /// <param name="value"></param>
        private void SetValue(int value)
        {
            if (!Enabled) return;
            
            _value = value;
            OnValueChanged?.Invoke(_value);
            RefreshStars();
        }

        /// <summary>
        /// 初始化星星
        /// </summary>
        private void InitStars()
        {
            _stars = GetComponentsInChildren<UIRatingStarItem>();
            UIRatingStarItem star = null;
            for (int i = 0; i < _stars.Length; i++)
            {
                star = _stars[i];
                star.Value = false;
                star.OnClickStar = OnClickStarEvent;
            }
        }


        private void OnClickStarEvent(int id)
        {
            Value = id;
        }


        /// <summary>
        /// 刷新所有的星星
        /// </summary>
        private void RefreshStars()
        {
            UIRatingStarItem star = null;
            for (int i = 0; i < _stars.Length; i++)
            {
                star = _stars[i];
                star.Value = star.Id <= Value;
            }
        }



        #endregion

        #region 设置多语言

        private void SetIsRTL(bool value)
        {
            _isRtl = value;
            _layout.reverseArrangement = value;
        }


        #endregion
    }
}