#nullable enable


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

    [StepType(StepTypeAttribute.OperatorStep)]
    public class Fold : OutputStep<double>
    {
        [UnityEngine.SerializeField]
        SinglePort<IEnumerable<double>> _in = new();

        [UnityEngine.SerializeReference, CareBoo.Serially.ShowSerializeReference]
        public IResourceOperator? Operator;
        public double GetDefault() {
            const double DefaultVal = 0;
            return DefaultVal;
        }
        public override double Run(EffectInput blackBoard) {
            if (!IsValid || Operator == null) {
                UnityEngine.Debug.LogError($"{this} Inner types are null");
                return GetDefault();
            }
            if (_in.Node == null) {
                return GetDefault();
            }

            return _in.Node.Run(blackBoard).DefaultIfEmpty(GetDefault()).Aggregate((current, next) => Operator.Operate(current, next));
        }

        public override IEnumerable<IPort> Inputs {
            get {
                yield return _in;
            }
        }

        public override string ToString() {
            var operatorName = Operator == null ? "*" : Operator.GetType().Name;

            return $"Fold.{operatorName}";
        }

        public override bool IsValid => Operator != null;
        public override EffectStepNodeData ToData() {
            var effectStepNodeData = base.ToData();
            effectStepNodeData.Operator = Operator;
            return effectStepNodeData;
        }

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

}