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

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

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

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

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

        public Enum GetEnum(string markerItem)
        {
            return Enum.Parse<BasicResourceType>(markerItem, true);
        }

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

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

        public float GetValue(UnitObject unit, string markerItem)
        {
            return unit.basicData.maxResources.Get(Enum.Parse<BasicResourceType>(markerItem, true));
        }

        public void UpdateWithValue(UnitObject unit, string markerItem, float formulaValue)
        {
            var @enum = Enum.Parse<BasicResourceType>(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.basicData.maxResources.Set(@enum, newValue);

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