#nullable enable


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

    [Serializable]
    public class MultiPort<PortType> : IPort
    {
        public List<OutputStep<PortType>> Nodes = new();

        public PortCapacity Capacity => PortCapacity.Multi;

        public string? DisplayName { get; set; }

        public IEnumerable<EffectStepNode> Connections() {
            return Nodes;
        }

        public void DisconnectAll() {
            Nodes.Clear();
        }

        public bool FromData(PortData portData, Dictionary<string, EffectStepNode> guidToNode) {
            DisplayName = portData.DisplayName;
            foreach (var connectedNodeGuid in portData.ConnectedNodesGuid) {
                TryConnect(guidToNode.GetValueOrDefault(connectedNodeGuid));
            }

            return true;
        }

        public bool IsAllowedConnect(EffectStepNode node) {
            return node is OutputStep<PortType>;
        }

        public PortData ToData() {
            return new() {
                Type = new(typeof(MultiPort<PortType>)),
                DisplayName = DisplayName,
                ConnectedNodesGuid = Nodes.Select(node => node.Guid).ToList(),
            };
        }

        public bool TryConnect(EffectStepNode node) {
            var success = false;
            if (IsAllowedConnect(node)) {
                Nodes.Add((OutputStep<PortType>)node);
                success = true;
            }

            return success;
        }

        public bool TryDisconnect(EffectStepNode value) {
            var success = false;
            var inputNode = value as OutputStep<PortType>;
            if (inputNode != null) {
                Nodes.Remove(inputNode);
                success = true;
            }

            return success;
        }
    }
}