﻿using System.Collections.Generic;
using EnergyShell.NetCore.Messages;
using Lidgren.Network;
using ShellUtil.Logging;
using ShellUtil.Serialization;

namespace EnergyShell.NetCore.Client
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class ClientMessageProcessor
    {
        /// <summary>
        /// The serializer used for net messages.
        /// </summary>
        private readonly ByteSerializer serializer;

        /// <summary>
        /// Initializes a new instance of the <see cref="ClientMessageProcessor"/> class.
        /// </summary>
        public ClientMessageProcessor()
        {
            this.serializer = new ByteSerializer();
        }

        /// <summary>
        /// Processes the recieved messages on the given server object.
        /// </summary>
        /// <param name="server">The server object to process message on.</param>
        public void ProcessMessages(NetServer server)
        {
            List<NetIncomingMessage> messageQueue = new List<NetIncomingMessage>();
            server.ReadMessages(messageQueue);
            foreach (NetIncomingMessage message in messageQueue)
            {
                switch (message.MessageType)
                {
                    case NetIncomingMessageType.ConnectionApproval:
                        ProcessConnectionApprovals(message);
                        break;
                    default:
                        Logger.Log("Ignored a net message because the given NetIncomingMessageType is not supported");
                        break;
                }
                ClientGameStateMessage gameState =
                    (ClientGameStateMessage)this.serializer.ByteArrayToObject(message.Data);
            }
        }

        /// <summary>
        /// Processes message for client connection approvals.
        /// </summary>
        /// <param name="message">The connection approval message to process.</param>
        private void ProcessConnectionApprovals(NetIncomingMessage message)
        {
            if (message.MessageType != NetIncomingMessageType.ConnectionApproval)
            {
                Logger.Log("Cannot process a message for connection approval because it is the wrong message type");
                return;
            }
            message.SenderConnection.Approve();
        }
    }
}
