using JiouSDP.Models;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace JiouSDP
{
    /// <summary>
    /// 响应客户端的消息
    /// </summary>
    public abstract class IResponseMessage
    {
        protected Uri Url;
        protected CommonModel commonModel;
        protected NameValueCollection param;

        /// <summary>
        /// 处理相应的逻辑
        /// </summary>
        /// <param name="commonModel">公共参数集合</param>
        /// <param name="param">请求的所有参数集合</param>
        /// <returns>返回消息给客户端</returns>
        public abstract HttpResponseMessage Api(CommonModel commonModel, NameValueCollection param);

        public HttpResponseMessage CallApi(Uri url, CommonModel commonModel, NameValueCollection param)
        {
            try
            {
                this.commonModel = commonModel;
                this.param = param;
                this.Url = url;
                HttpResponseMessage rm = Api(commonModel, param);

                return rm;
            }
            catch (Exception ex)
            {
                return ToResponseMessage(ex.Message, this.Url, this.commonModel, this.param);
            }
        }
        /// <summary>
        /// 转HttpResponseMessage消息
        /// </summary>
        /// <param name="obj">返回的类型</param>
        /// <returns></returns>
        public HttpResponseMessage ToResponseMessage(object obj)
        {
            return ToResponseMessage(obj, this.Url, this.commonModel, this.param);
        }

        /// <summary>
        /// 转HttpResponseMessage消息
        /// </summary>
        /// <param name="obj">返回的类型</param>
        /// <returns></returns>
        public static HttpResponseMessage ToResponseMessage(object obj, Uri url, CommonModel commonModel, NameValueCollection param)
        {
            string str = string.Empty;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json")
            };
            string log = "请求:";
            if (url != null)
            {
                log += url.ToString();
            }
            if (param != null)
            {
                log += "?" + param.ToString();
            }
            log += "\r\n返回:" + str;
            if (commonModel != null)
                RFramework.Log.Write(string.Format("userid:{0},log:{1}",commonModel.userid, log));
            return result;
        }
    }
}