using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace LJLib.HttpServer
{
    public abstract class LJHttpServer
    {

        private readonly int _port;
        TcpListener _listener;
        bool is_active = true;

        protected LJHttpServer(int port)
        {
            _port = port;
        }

        public void Listen()
        {
            _listener = new TcpListener(IPAddress.Any, _port);
            _listener.Start();
            ThreadPool.QueueUserWorkItem(state =>
            {
                // 侦听线程
                Thread.CurrentThread.IsBackground = false;
                try
                {
                    while (is_active)
                    {
                        if (_listener.Pending())
                        {
                            TcpClient s = _listener.AcceptTcpClient();
                            ThreadPool.QueueUserWorkItem(st =>
                            {
                                try
                                {
                                    Thread.CurrentThread.IsBackground = true;
                                    LJHttpProcessor processor = new LJHttpProcessor(s, this);
                                    processor.Process();
                                }
                                catch (System.Exception e)
                                {
                                    Trace.Write("HTTP请求处理线程异常退出:" + e.ToString());
                                }
                            });
                        }
                        else
                        {
                            Thread.Sleep(100);
                        }
                    }
                }
                catch (System.Exception e)
                {
                    Trace.Write("HTTP监听异常退出:" + e.ToString());
                }

            });
        }

        public void Stop()
        {
            is_active = false;
        }

        public abstract void HandleGetRequest(LJHttpProcessor p);
        public abstract void HandlePostRequest(LJHttpProcessor p, StreamReader inputData);
    }
}
