using System;
using System.Collections.Generic;
using System.Linq;
using Sirenix.Utilities;
using VOID.Generic.Dict;
using VOID.Generic.Objects.Unit.Events;
using VOID.Generic.Status.Effect;

namespace VOID.Generic.Objects.Unit.DataCalculator
{
    public class UnitResourceCalcGroup : ICalcGroup
    {
        public string GetMarkerGroup()
        {
            return "UnitResource";
        }

        public IEnumerable<string> GetMarkerItems()
        {
            return GetEnums().Select(@enum => @enum.ToString());
        }

        public Type GetEnumType()
        {
            return typeof(UnitResourceType);
        }

        public IEnumerable<Enum> GetEnums()
        {
            return Enum.GetValues(GetEnumType()).OfType<Enum>();
        }

        public Enum GetEnum(string markerItem)
        {
            return Enum.Parse<UnitResourceType>(markerItem);
        }

        public float GetEffectValue(UnitObject unit, string markerItem)
        {
            var @enum = Enum.Parse<UnitResourceType>(markerItem, true);
            return unit.statusManager.GetStatuses()
                .SelectMany(status => status.effects)
                .FilterCast<PointChangeUnitResourceEffect>()
                .Where(effect => effect.unitResourceType == @enum)
                .Select(effect => effect.pointModificator)
                .Sum();
        }

        public float GetBaseValue(UnitObject unit, string markerItem)
        {
            return unit.unitData.baseMaxResources.Get(Enum.Parse<UnitResourceType>(markerItem, true));
        }

        public float GetValue(UnitObject unit, string markerItem)
        {
            return unit.unitData.baseMaxResources.Get(Enum.Parse<UnitResourceType>(markerItem, true));
        }

        public void UpdateWithValue(UnitObject unit, string markerItem, float formulaValue)
        {
            var @enum = Enum.Parse<UnitResourceType>(markerItem, true);
            var baseValue = GetBaseValue(unit, markerItem);
            var effectValue = GetEffectValue(unit, markerItem);
            var previousValue = GetValue(unit, markerItem);
            var newValue = baseValue + effectValue + formulaValue;
            var diffValue = newValue - previousValue;
            unit.unitData.maxResources.Set(@enum, newValue);

            unit.unitEvents.onMaxResourceChange.Invoke(
                new UnitResourceChangeEvent()
                {
                    unit = unit,
                    type = @enum,
                    changedValue = diffValue,
                    newValue = newValue,
                    oldValue = previousValue
                }
            );
        }
    }
}