using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Mall.IM.Util
{
    public class ApiRequestUtil
    {
        private static readonly String APP_KEY = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("ImKey").Value;
        private static readonly String APP_SECRET = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("ImSecret").Value;

        /// <summary>
        /// 发起post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceAddress">服务器接口请求地址</param>
        /// <param name="postData">post数据</param> 
        /// <returns></returns>
        public static ResultResponse<T> PostResponse<T>(string serviceAddress, String postData)
           where T : class, new()
        {
            var httpClient = new RestClient(serviceAddress);
            var request = new RestRequest(postData, Method.POST);
            String nonce = "viitto2018";
            String curTime = CheckSumBuilderUtil.GetCurentTimeTicks();
            String checkSum = CheckSumBuilderUtil.GetCheckSum(APP_SECRET, nonce, curTime);
            
            request.AddHeader("AppKey", APP_KEY);
            request.AddHeader("Nonce", nonce);
            request.AddHeader("CurTime", curTime);
            request.AddHeader("CheckSum", checkSum);
            request.AddHeader("ContentType", "application/x-www-form-urlencoded;charset=utf-8");


            var restResponse = httpClient.Execute<T>(request);
            //    restResponse.
            ResultResponse<T> response = new ResultResponse<T>();
            response.HttpStatusCode = restResponse.StatusCode;
            response.Data = restResponse.Data;

            return response;
        }
    }
    /// <summary>
    /// 网易IM接口请求返回数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ResultResponse<T>
    {
        /// <summary>
        /// HTTP请求Code
        /// </summary>
        public HttpStatusCode HttpStatusCode { get; set; }

        /// <summary>
        /// 请求返回的数据
        /// </summary>
        public T Data { get; set; }
    }
}
