using FishNet.Object;
using FishNet.Object.Synchronizing;
using IStalk.Data;

namespace IStalk.Shared
{
    public class WeightComponent : NetworkBehaviour
    {
        private readonly SyncVar<float> _currentWeight = new();

        public float CurrentWeight => _currentWeight.Value;
        public WeightTier CurrentTier => GlobalRules_SO.Instance.GetTier(_currentWeight.Value);
        public float SpeedMultiplier => GlobalRules_SO.Instance.GetSpeedMultiplier(CurrentTier);

        public event System.Action<float, WeightTier> OnWeightChanged;

        public override void OnStartNetwork()
        {
            base.OnStartNetwork();
            _currentWeight.OnChange += HandleWeightSynced;
        }

        private void HandleWeightSynced(float prev, float next, bool asServer)
        {
            OnWeightChanged?.Invoke(next, GlobalRules_SO.Instance.GetTier(next));
        }

        [Server]
        public void AddWeight(float amount)
        {
            _currentWeight.Value += amount;
        }

        [Server]
        public void RemoveWeight(float amount)
        {
            _currentWeight.Value = UnityEngine.Mathf.Max(0, _currentWeight.Value - amount);
        }

        [Server]
        public void SetWeight(float value)
        {
            _currentWeight.Value = UnityEngine.Mathf.Max(0, value);
        }
    }
}
