using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Foundation;

namespace com.hdl.on
{
    public class Server
    {
        public static int Port=22222;
		static System.Net.HttpListener listener;

        /// <summary>
        /// 启动监听及处理
        /// </summary>
        internal static void Start(System.Net.IPAddress ipAddress)
        {
            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    if (listener == null)
                    {
                        listener = new System.Net.HttpListener();

                        listener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;

                        listener.Prefixes.Add(string.Format("http://{0}:{1}/", ipAddress.ToString(), Port));

                        listener.Start();

                        beginGetContext(listener);

                        System.Console.WriteLine("音乐服务启动成功!");
                    }
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("音乐服务启动失败!" + e.Message);
                }
                finally { }
            });
        }

        internal static void Stop()
        {
            if (listener != null)
            {
                try
                {
                    listener.Close();
                }catch{}
            }
            listener = null;
            System.Console.WriteLine("音乐服务停止!");
        }
        static string getTempPath()
        {
            var dirs = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true);
            if (dirs == null || dirs.Length == 0)
            {
                return "";
            }
            return dirs[0];
        }
        /// <summary>
        /// 开始异步接收http请求
        /// </summary>
        /// <param name="listerner"></param>
        static void beginGetContext(System.Net.HttpListener listerner)
        {
            try
            {

                if (listerner == null || !listerner.IsListening)
                {
                    return;
                }
                listerner.BeginGetContext(new System.AsyncCallback(getContextCallBack), null);

            }
            catch
            {
                System.Threading.Thread.Sleep(1);
                beginGetContext(listerner);
            }
        }

        /// <summary>
        /// 获取http请求,并处理
        /// </summary>
        /// <param name="ar"></param>
        static void getContextCallBack(System.IAsyncResult ar)
        {
            beginGetContext(listener);
            try
            {
                System.Net.HttpListenerContext context = listener.EndGetContext(ar);
                manager(context);
            }
            catch { }

        }


        static void manager(System.Net.HttpListenerContext httpListenerContext)
        {
            System.Net.HttpListenerResponse httpListenerResponse = null;

            try
            {
                #region
                httpListenerResponse = httpListenerContext.Response;

                httpListenerResponse.StatusCode = 200;//设置返回给客服端http状态代码
                httpListenerResponse.ContentEncoding = System.Text.Encoding.UTF8;


                var nameValueCollection = HttpUtility.ParseQueryString(System.IO.Path.GetFileName(httpListenerContext.Request.RawUrl));
                if (0 < nameValueCollection.Count && System.IO.File.Exists($"{getTempPath()}/{nameValueCollection[0]}"))
                {
                    var file = new System.IO.FileStream($"{getTempPath()}/{nameValueCollection[0]}", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    try
                    {
                        while (file.CanRead)
                        {
                            var bytes = new byte[1024];
                            var len = file.Read(bytes, 0, bytes.Length);
                            httpListenerResponse.OutputStream.Write(bytes, 0, len);
                        }
                    }
                    finally
                    {
                        file.Close();
                    }
                }
                httpListenerResponse.OutputStream.Flush();
                #endregion
            }
            catch
            {

            }
            finally
            {
                #region
                try
                {
                    httpListenerContext.Request.InputStream.Close();
                }
                catch { }

                try
                {
                    httpListenerResponse.OutputStream.Close();
                }
                catch { }


                try
                {
                    httpListenerResponse.Close();
                }
                catch { }

                #endregion
            }
        }
    }
}