using System;
using System.Collections.Generic;

namespace Passer.Control.Core {

    public class RemoteParticipant {
        public string ipAddress = "0.0.0.0";
        public int port = 0;

        public byte networkId;

        public RemoteParticipant() {

        }
        public RemoteParticipant(string ipAddress, int port) {
            this.ipAddress = ipAddress;
            this.port = port;
        }

        protected readonly List<Thing> things = new();

        public Thing Get(byte networkId, byte thingId) {
            Thing thing = things.Find(aThing => Thing.IsThing(aThing, networkId, thingId));
            // if (thing == null)
            //     Console.WriteLine($"Could not find thing {ipAddress}:{port}[{networkId}/{thingId}]");
            return thing;
        }

        public void Add(Thing thing, bool invokeEvent = true) {
            // Console.WriteLine($"added thing [{thing.networkId}/{thing.id}]"); 
            Thing foundThing = Get(thing.networkId, thing.id);

            if (foundThing == null) {
                things.Add(thing);

                if (invokeEvent)
                    Thing.InvokeNewThing(thing);
                // Console.Write($"Add thing {ipAddress}:{port}[{networkId}/{thing.id}]");
            } else {
                if (thing != foundThing) {
                    // should be: find first non-existing id...
                    thing.id = (byte)this.things.Count;
                    things.Add(thing);
                    // Console.Write($"Add thing, updated thing id to [{thing.networkId}/{thing.id}]");
                }
            }
        }

    }

}