using PlantBox.Shared.Communication.Commands;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace PlantBox.Shared.Communication
{
    /// <summary>
    /// Wrap a <see cref="NetworkStream"/> to send <see cref="CommandPacket"/> easily, see Wiki > Protocol
    /// </summary>
    public class CommandStream : IDisposable
    {
        private NetworkStream _stream;

        /// <summary>
        /// Create a new <see cref="CommandStream"/>
        /// </summary>
        /// <param name="networkStream">A connected and valid <see cref="NetworkStream"/></param>
        public CommandStream(NetworkStream networkStream)
        {
            _stream = networkStream;
        }

        /// <summary>
        /// Release resources associated with the underlying stream
        /// </summary>
        public void Dispose()
        {
            _stream.Dispose();
        }

        /// <summary>
        /// Read a <see cref="CommandPacket"/> from the stream
        /// </summary>
        /// <returns></returns>
        public CommandPacket Receive()
        {
            // Length
            byte[] buffer = new byte[4];
            _stream.Read(buffer, 0, buffer.Length);

            uint length = BitConverter.ToUInt32(buffer, 0);

            // Data
            buffer = new byte[length];
            int position = 0;

            while (position < length)
            {
                int bytesToRead = Math.Min(Connection.BUFFER_SIZE, (int)length - position);

                int bytesRead = _stream.Read(buffer, position, bytesToRead);

                position += bytesRead;
            }

            string[] packet = Encoding.UTF8.GetString(buffer).Split('\n');

            if (!Enum.TryParse(packet[0], true, out Command command))
            {
                command = Command.Invalid;
            }

            return new CommandPacket(command, packet[1].Split(';'));
        }

        /// <summary>
        /// Read a <see cref="CommandPacket"/> from the stream and deserialize data to a <see cref="CommandSerializable{T}"/>
        /// </summary>
        /// <typeparam name="T">A valid <see cref="CommandSerializable{T}"/></typeparam>
        /// <returns></returns>
        public (CommandPacket, T) Receive<T>() where T : CommandSerializable<T>, new()
        {
            var packet = Receive();

            return (packet, new T().Deserialize(packet.Arguments));
        }

        /// <summary>
        /// Read a <see cref="CommandPacket"/> from the stream asynchronously
        /// </summary>
        /// <returns></returns>
        public async Task<CommandPacket> ReceiveAsync()
        {
            // Length
            byte[] buffer = new byte[4];
            await _stream.ReadAsync(buffer, 0, buffer.Length);

            uint length = BitConverter.ToUInt32(buffer, 0);

            // Data
            buffer = new byte[length];
            int position = 0;

            while (position < length)
            {
                int bytesToRead = Math.Min(Connection.BUFFER_SIZE, (int)length - position);

                int bytesRead = await _stream.ReadAsync(buffer, position, bytesToRead);

                position += bytesRead;
            }

            string[] packet = Encoding.UTF8.GetString(buffer).Split('\n');

            if (!Enum.TryParse(packet[0], true, out Command command))
            {
                command = Command.Invalid;
            }

            return new CommandPacket(command, packet[1].Split(';'));
        }

        /// <summary>
        /// Read a <see cref="CommandPacket"/> from the stream and deserialize data to a <see cref="CommandSerializable{T}"/> asynchronously
        /// </summary>
        /// <typeparam name="T">A valid <see cref="CommandSerializable{T}"/></typeparam>
        /// <returns></returns>
        public async Task<(CommandPacket, T)> ReceiveAsync<T>() where T : CommandSerializable<T>, new()
        {
            var packet = await ReceiveAsync();

            return (packet, new T().Deserialize(packet.Arguments));
        }

        /// <summary>
        /// Write a <see cref="CommandPacket"/> in the stream
        /// </summary>
        /// <param name="command"></param>
        public void Send(CommandPacket command)
        {
            string packet = command.ToString();
            byte[] data = Encoding.UTF8.GetBytes(packet);
            uint length = (uint)data.Length;

            // Length
            _stream.Write(BitConverter.GetBytes(length), 0, 4);

            // Data
            int position = 0;

            while (position < length)
            {
                int bytesToWrite = Math.Min(Connection.BUFFER_SIZE, (int)length - position);

                _stream.Write(data, position, bytesToWrite);

                position += bytesToWrite;
            }
        }

        /// <summary>
        /// Write a <see cref="CommandPacket"/> in the stream asynchronously
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task SendAsync(CommandPacket command)
        {
            string packet = command.ToString();
            byte[] data = Encoding.UTF8.GetBytes(packet);
            uint length = (uint)data.Length;

            // Length
            await _stream.WriteAsync(BitConverter.GetBytes(length), 0, 4);

            // Data
            int position = 0;

            while (position < length)
            {
                int bytesToWrite = Math.Min(Connection.BUFFER_SIZE, (int)length - position);

                await _stream.WriteAsync(data, position, bytesToWrite);

                position += bytesToWrite;
            }
        }
    }
}
