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

namespace Apewer.Network
{

    /// <summary></summary>
    public class HttpServer
    {

        private HttpListener _listener;
        private Thread _thread;
        private int _port = 80;

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

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

        /// <summary></summary>
        public Exception Start(int port)
        {
            _listener = new HttpListener();
            try
            {
                _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                _listener.Prefixes.Add("http://0.0.0.0:" + port.ToString() + "/");
                _listener.Start();

                _thread = new Thread(Listen);
                _thread.IsBackground = true;
                _thread.Start();

                return null;
            }
            catch (Exception e)
            {
                return e;
            }
        }

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

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

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

                var context = _listener.GetContext();
                var thread = new Thread((obj) =>
                {
                    try { Action?.Invoke(context); }
                    catch (Exception e) { var __e = e; }
                })
                {
                    IsBackground = true
                };
                thread.Start(context);
            }
        }

    }

}