﻿using System.Collections.Generic;
using System.Linq;
using WhormholeExtreme.BaseClasses;
using WhormholeExtreme.Extensions;

namespace WhormholeExtreme.Behaviour2
{
    public partial class NetworkBehaviour
    {
        #region GetNearestEndPointModule
        public static NetworkEndPointModule GetNearestEndPointModule(NetworkControlModule module)
        {
            if (module == null) return null;

            return GetNearestEndPointModule(module.Position, module.range);
        }
        public static NetworkEndPointModule GetNearestEndPointModule(Vector3d sourcePoint, double maxDistance)
        {
            NetworkEndPointModule nearestEndPoint = null;

            if (sourcePoint == null) return nearestEndPoint;

            double distance = 0;
            double minDistance = maxDistance;

            foreach (NetworkRegistrationModule module in NetworkBehaviour.Instance.RegisteredModules)
            {
                if (module is NetworkEndPointModule)
                {
                    distance = sourcePoint.GetDistance(module.Position);

                    if (distance <= minDistance)
                    {
                        minDistance = distance;
                        nearestEndPoint = (NetworkEndPointModule)module;
                    }
                }
            }

            return nearestEndPoint;
        }
        #endregion

        private static NetworkEndPointModule GetCurrentDestination(NetworkEndPointModule module)
        {
            NetworkEndPointConnection connection = NetworkBehaviour.Instance.RegisteredConnections.Where(c => c.Source == module).FirstOrDefault();

            if (connection != null) return connection.Destination;

            return null;
        }

        public static List<NetworkEndPointModule> GetPossibleDestinations(NetworkEndPointModule sourceEndPoint)
        {
            List<NetworkEndPointModule> endPoints = new List<NetworkEndPointModule>();

            NetworkEndPointModule endPoint;
            foreach (NetworkRegistrationModule module in NetworkBehaviour.Instance.RegisteredModules)
            {
                if (module is NetworkEndPointModule)
                {
                    endPoint = (NetworkEndPointModule)module;
#if DEBUG

#else
                    if (endPoint == sourceEndPoint) continue;
#endif

                    if (GetEndPointConnection(endPoint) == null) endPoints.Add(endPoint);
                }
            }

            return endPoints;
        }

        public static void OnNetworkEndPointModuleOutOfEnergy(NetworkEndPointModule sender)
        {
            NetworkBehaviour.TryCloseConnection(sender);
        }
    }
}