
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpServer
{
    class MyHttpServer : HttpServerBase
    {
        public MyHttpServer(int maxThreads) : base(maxThreads)
        { }

        protected override void ProcessHttpRequest(HttpListenerContext context)
        {
            var request = context.Request;
            var response = context.Response;

            context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式，编码为UTF-8            
            context.Response.AddHeader("Content-type", "application/json;charset=UTF-8");//添加响应头信息
            context.Response.ContentEncoding = Encoding.UTF8;

            string returnObj = null;//定义返回客户端的信息
            if (request.HttpMethod == "POST" && request.InputStream != null)
            {
                 returnObj = HandleRequest(request, response);
                //处理客户端发送的请求并返回处理信息                
            }
            else
            {
                returnObj = "不是post请求或者传过来的数据为空";
            }
            var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码
            try
            {
                using (var stream = response.OutputStream)
                {
                    //把处理信息返回到客户端
                    stream.Write(returnByteArr, 0, returnByteArr.Length);
                }
            }
            catch (Exception ex)            
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("The network crashed：{0}", ex.ToString());

            }
            //Console.ForegroundColor = ConsoleColor.Yellow;
           // Console.WriteLine("\r\n请求处理完成,,时间：{0}", DateTime.Now.ToString());


               
        }
        private static string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
        {
            string HttpBodydata = null;
            try
            {
                var byteList = new List<byte>();
                var byteArr = new byte[2048];
                int readLen = 0;
                int len = 0;
                //接收客户端传过来的数据并转成字符串类型
                do
                {
                    readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);
                    len += readLen;
                    byteList.AddRange(byteArr);
                } while (readLen != 0);
                HttpBodydata = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);

                //获取得到数据data可以进行其他操作
            }
            catch (Exception ex)
            {
                response.StatusDescription = "404";
                response.StatusCode = 404;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("在接收数据时发生错误:{0}",ex.ToString());
                return "在接收数据时发生错误:{0}"+ex.ToString();//把服务端错误信息直接返回可能会导致信息不安全，此处仅供参考
            }
            //Get Bodydata field string
            string[] FiledStr = new string[10];
            FiledStr = HttpBodydata.Split('&');
            //int nFieldCount=FiledStr.Length;

            string HTTPAPI_OpenString="/api/Device/OpenDoor";
            string HTTPAPI_EventString="/api/Device/DoorEvent";
            string HTTPAPI_HeartString="/api/Device/DoorHeart";
            int i=0;
            string AnswerStrOK;
            if(String.Compare(request.Url.AbsolutePath, HTTPAPI_OpenString) == 0)//HTTPAPI_OpenString
            {
                //HttpBodydata
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("HTTP Open receive data:");
                for (i = 0; i < FiledStr.Count(); i++)
                {
                    Console.WriteLine("{0}", FiledStr[i]);
                }
                AnswerStrOK = "{\"ResultCode\":\"1\",\"ActIndex\":\"1\",\"Msg\":\"Success\",\"Audio\":\"04\"}";
            }
            else if(String.Compare(request.Url.AbsolutePath, HTTPAPI_EventString) == 0)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("HTTP Event receive data:");
                for (i = 0; i < FiledStr.Count(); i++)
                {
                    Console.WriteLine("{0}", FiledStr[i]);
                }
                AnswerStrOK = "{\"ResultCode\":\"1\",\"Msg\":\"Event_Success\"}";
                
            }
            else if(String.Compare(request.Url.AbsolutePath, HTTPAPI_HeartString) == 0)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("HTTP heartbeat receive data:");
                for (i = 0; i < FiledStr.Count(); i++)
                {
                    Console.WriteLine("{0}", FiledStr[i]);
                }
                AnswerStrOK = "{\"ResultCode\":\"1\",\"CorrectTime\":\"220301103001\",\"Msg\":\"HeartBeatOK\"}";
                
            }
            else
            {
                response.StatusDescription = "404";
                response.StatusCode = 404;
                return "API uri error";//把服务端错误信息直接返回可能会导致信息不安全，此处仅供参考
            }


            response.StatusDescription = "OK";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
            response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
            //response.
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\r\n接收数据完成:{0},\r\n时间：{1}",HttpBodydata.Trim(),DateTime.Now.ToString());

            return AnswerStrOK;
        }
    }
}