#nullable enable


namespace TagFighter.Effects.Steps
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    [StepType(StepTypeAttribute.GetterStep)]
    public class PawnResourceGet : OutputStep<IEnumerable<double>>
    {
        [CareBoo.Serially.TypeFilter(derivedFrom: typeof(Resources.Resource<>))]
        public CareBoo.Serially.SerializableType? Resource;

        public override IEnumerable<double> Run(EffectInput blackBoard) {
            if (!IsValid || Resource == null) {
                UnityEngine.Debug.Log($"{this} Inner types are null");
                return blackBoard.Affected.Select(transform => 0d);
            }

            var getSpecificMethod = typeof(PawnResourceGet).GetMethod(nameof(GetSpecific), BindingFlags.NonPublic | BindingFlags.Instance).
                                            MakeGenericMethod(Resource.Type, Resource.Type.BaseType.GetGenericArguments()[0]);
            var value = getSpecificMethod.Invoke(this, new object[] { blackBoard });

            return (IEnumerable<double>)value;
        }

        IEnumerable<double> GetSpecific<TResource, TUnitType>(EffectInput blackBoard)
            where TResource : Resources.Resource<TUnitType>
            where TUnitType : Resources.IUnitType {
            return blackBoard.Affected.Select(transform => (double)transform.GetComponent<TResource>().GetCurrent().AsPrimitive());
        }
        public override IEnumerable<IPort> Inputs => Enumerable.Empty<IPort>();

        public override string ToString() {
            var resourceName = Resource == null || Resource.Type == null ? "*" : Resource.Type.Name;
            var statName = "Current";

            return $"Pawn.Get.{resourceName}.{statName}";
        }

        public override bool IsValid {
            get {
                return Resource != null && Resource.Type != null;
            }
        }
        public override EffectStepNodeData ToData() {
            var effectStepNodeData = base.ToData();
            effectStepNodeData.Resource = Resource;
            // effectStepNodeData.Register = Register;
            return effectStepNodeData;
        }

        public override bool FromData(EffectStepNodeData effectStepNodeData, Dictionary<string, EffectStepNode> guidToNode) {
            base.FromData(effectStepNodeData, guidToNode);
            Resource = effectStepNodeData.Resource;
            // Register = effectStepNodeData.Register;
            return true;
        }

    }

}