using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading.Tasks;

using parkMonitor.Tools;
using parkMonitor.entity;

namespace parkMonitor.server.WebThread
{
    public class MultiSocketThread
    {
        public TcpClient tcpClient { get; set; }
        public NetworkStream ns { get; set; }
        private MessageUTF8 message = null;

        public MultiSocketThread(TcpClient tcpClient)
        {
            this.tcpClient = tcpClient;
            ns = tcpClient.GetStream();
            message = new MessageUTF8();
            message.cmd = '0';

        }

        public MultiSocketThread()
        {
            // TODO: Complete member initialization
        }

        public void SendMessage(AbstractMessage message)
        {
            byte[] byteMessage = JsonByByteToObjectTools.ObjToJsonByte(message);
            ns.Write(byteMessage, 0, byteMessage.Length);
            ns.Flush();
        }

        public AbstractMessage ReceiverMessage()
        {
            try
            {
                byte[] bytes = new byte[256];
                int bytesRead = ns.Read(bytes, 0, bytes.Length);
                message = (MessageUTF8)JsonByByteToObjectTools.JsonByteToObj<MessageUTF8>(bytes);
                ns.Flush();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return message;
        }

        public void Run()
        {
            //int i = 2;
            //while (i-- > 0)
            //{
                SendMessage(message);

                MessageUTF8 msg = (MessageUTF8)ReceiverMessage();

                CentralForWeb.blockingQueue.Enqueue(msg);

            //}
        }
        public void Close()
        {
            ns.Close();
        }

    }
}
