using System;
using XGame.Database;
using XGame.Framework;

namespace FL.Battle
{
    public class EntityAttributes : IDisposable
    {
        public int TableId { get; private set; }
        public long UID { get; private set; }
        public string Name { get; set; }
        /// <summary>
        /// 基础生命
        /// </summary>
        public long BasicHp => GetValue(EAttributeType.Hp);
        public long HpLimit => GetValue(EAttributeType.HpTotal);
        /// <summary>
        /// 当前生命值
        /// </summary> 
        public long CurrentHp { get; set; }
        public long Mp { get; set; }
        public long MpLimit { get; set; }
        public float Radius { get; set; }
        /// <summary>
        /// 移动速度，不带缩放
        /// </summary>
        public float MoveSpeed => GetValue(EAttributeType.Speed);
        /// <summary>
        /// 移动速度缩放值
        /// EAttributeType.SpeedAdd 最低值必须大于 -10000
        /// </summary>
        public float MoveSpeedScale
        {
            get
            {
                var scale = 1 + (float)GetValue(EAttributeType.SpeedAdd).ToRealDouble();
                return scale < 0 ? 0 : scale;
            }
        }
        /// <summary>
        /// 移动时间缩放值
        ///  EAttributeType.SpeedAdd 最低值必须大于 -10000
        /// </summary>
        public float MoveTimeScale => 1 / MoveSpeedScale;
        /// <summary>
        /// 真实的移动速度
        /// 慎用
        /// </summary>
        public float MoveSpeedReal => MoveSpeed * MoveSpeedScale;
        public int Attack { get => (int)GetValue(EAttributeType.Atk); }
        public int AttackCD { get; set; }

        private Attributes _staticAttr;
        /// <summary>
        /// 静态属性，战斗外基础数值
        /// 战斗内不会变
        /// </summary>
        public Attributes Static => _staticAttr ??= ObjectPool.Acquire<Attributes>();
        private Attributes _dynamicAttr;
        /// <summary>
        /// 动态属性，战斗内属性加成
        /// </summary>
        public Attributes Dynamic => _dynamicAttr ??= ObjectPool.Acquire<Attributes>();

        public EntityAttributes(int tableId, long uid)
        {
            TableId = tableId;
            UID = uid;
        }
        public long GetValue(EAttributeType type)
        {
            return Static.GetValue(type) + (_dynamicAttr?.GetValue(type) ?? 0);
        }
        void IDisposable.Dispose()
        {
            if (_staticAttr != null)
            {
                ObjectPool.Recycle(_staticAttr);
                _staticAttr = null;
            }
            if (_dynamicAttr != null)
            {
                ObjectPool.Recycle(_dynamicAttr);
                _dynamicAttr = null;
            }
        }
        public void CopyFrom(Attributes attribute)
        {
            attribute.CopyTo(Static);
            CurrentHp = HpLimit;
        }
        public void ResetHp()
        {
            CurrentHp = HpLimit;
        }
    }
}
