using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Net;

namespace Apewer.Web
{

    /// <summary></summary>
    public class HttpListener
    {

        private System.Net.HttpListener _listener;
        private Thread _thread;
        private int _port = 80;
        private string _ip = "127.0.0.1";

        /// <summary></summary>
        public Action<HttpListenerContext> Action { get; set; }

        /// <summary></summary>
        public string IP
        {
            get { return _ip; }
            set { _ip = NetworkUtility.IsIP(value) ? value : "127.0.0.1"; }
        }

        /// <summary></summary>
        public int Port
        {
            get { return _port; }
            set { _port = Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, value)); }
        }

        /// <summary></summary>
        public Exception Start()
        {
            var prefix = $"http://{_ip}:{Port}/";
            Logger.Web.Info(this, $"准备在 {prefix} 启动。");

            _listener = new System.Net.HttpListener();
            try
            {
                _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                _listener.Prefixes.Add(prefix);
                _listener.Start();

                // 多线程方式处理请求。
                // _thread = new Thread(Listen);
                // _thread.IsBackground = true;
                // _thread.Start();

                // 异步方式处理请求。
                _listener.BeginGetContext(Received, null);

                Logger.Web.Info(this, $"已在 {prefix} 启动。");
                return null;
            }
            catch (Exception ex)
            {
                Logger.Web.Exception(this, ex);
                Logger.Web.Info(this, $"在 {prefix} 启动失败。");
                return ex;
            }
        }

        /// <summary></summary>
        public void Stop()
        {
            if (_thread != null)
            {
                // _thread.Abort();
                _thread = null;
            }

            if (_listener != null)
            {
                _listener.Close();
                _listener.Stop();
                _listener = null;
            }
        }

        void Received(IAsyncResult ar)
        {
            _listener.BeginGetContext(Received, null);

            var context = _listener.EndGetContext(ar);
            var action = Action;
            if (action != null) action(context);
        }

        void Listen()
        {
            while (true)
            {
                if (_listener == null) break;

                var context = _listener.GetContext();
                var action = Action;
                if (action == null) continue;
                action(context);
                // RuntimeUtility.InBackground(() => action(context), true);
            }
        }

    }

}