using BBWYB.Common.Http;
using BBWYB.Common.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;

namespace WebTest.APIServices
{
    public class BaseApiService
    {
        private RestApiService restApiService;

        protected GlobalContext globalContext;

        public BaseApiService(RestApiService restApiService, GlobalContext globalContext)
        {
            this.restApiService = restApiService;
            this.globalContext = globalContext;
        }

        protected ApiResponse<T> SendRequest<T>(string apiHost,
                                                string apiPath,
                                                object param,
                                                IDictionary<string, string> headers,
                                                HttpMethod httpMethod,
                                                string contentType = RestApiService.ContentType_Json,
                                                ParamPosition paramPosition = ParamPosition.Body,
                                                bool enableRandomTimeStamp = false)
        {
            try
            {
                if (headers == null)
                    headers = new Dictionary<string, string>();
                if (!headers.ContainsKey("ClientCode"))
                    headers.Add("ClientCode", "U");
                if (!headers.ContainsKey("ClientVersion"))
                    headers.Add("ClientVersion", "10000");
                if (!headers.ContainsKey("Authorization") && !string.IsNullOrEmpty(globalContext.UserToken))
                    headers.Add("Authorization", $"Bearer {globalContext.UserToken}");
                if (!headers.ContainsKey("qy"))
                    headers.Add("qy", "qy");

                var result = restApiService.SendRequest(apiHost, apiPath, param, headers, httpMethod, contentType, paramPosition, enableRandomTimeStamp);
                if (result.StatusCode != System.Net.HttpStatusCode.OK &&
                    result.Content.Contains("\"Success\"") &&
                    result.Content.Contains("\"Msg\"") &&
                    result.Content.Contains("\"Data\""))
                    throw new BusinessException($"{result.StatusCode} {result.Content}") { Code = (int)result.StatusCode };
                return JsonConvert.DeserializeObject<ApiResponse<T>>(result.Content);
            }
            catch (Exception ex)
            {
                return ApiResponse<T>.Error((ex is BusinessException) ? (ex as BusinessException).Code : 0, ex.Message);
            }
        }
    }
}