using ChatServer.util;
using System;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Threading;

namespace ChatServer
{
  class QueueUtil
  {
    private static ConcurrentQueue<Item> cq = new ConcurrentQueue<Item>();

    public static void Enqueue(Item state)
    {
      Console.WriteLine("enqueue state...");
      cq.Enqueue(state);
    }

    public static void StartDetecting()
    {
      Thread queueDetectingThread = new Thread(() =>
      {
        Console.WriteLine("Run Detecting queue...");

        Item item;

        while (true)
        {
          if (cq.TryDequeue(out item))
          {
            ThreadPool.QueueUserWorkItem(ProcessItem, item);
            item = null;
          }
        }
      });

      queueDetectingThread.Start();
    }

    // 메시지를 콘솔에 출력하고 클라이언트에게 돌려줌
    static void ProcessItem(object _item)
    {
      Item item = _item as Item;
      Socket clientSocket = item.State.workSocket;
      string message = item.Message;

      try
      {
        Console.WriteLine("<Dequeued Item>: {0}", message);
        if (clientSocket.Connected)
        {
          clientSocket.Send(item.Packet);
          if (item.Message.Equals(Constants.EXIT))
          {
            Console.WriteLine("연결 종료 요청...");
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
          }
        }
      }
      catch (Exception e)
      {
        Console.WriteLine(e);
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
      }
    }
  }
}
