using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;

namespace _Core
{
    public class HttpResponseBody {
        private UnityWebRequest requestHandler;
        private Dictionary<string, string> dic;
        public Texture2D ToImage() {
            Texture2D texture = new Texture2D(10, 10);
            texture.LoadImage(ToRaw());
            return texture;
        }
        public byte[] ToRaw() => requestHandler.downloadHandler.data;
        public string ToText() =>  requestHandler == null ? JsonConvert.SerializeObject(dic) : requestHandler.isNetworkError ? requestHandler.error : requestHandler.downloadHandler.text;
        public T ToJson<T>() {
            if(requestHandler == null)
            {
                return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(dic));
            }
            else
            {
                var text = requestHandler.downloadHandler.text;
                return JsonConvert.DeserializeObject<T>(text);
            }
        }
        public HttpResponseBody(UnityWebRequest requestHandler) {
            this.requestHandler = requestHandler;
        }

        public HttpResponseBody(Dictionary<string, string> dic) {
            this.dic = dic;
        }
    }
    
    public class HttpResponse
    {
        public int StatusCode => (int)requestHandler.responseCode;
        public Dictionary<string, string> Headers => requestHandler.GetResponseHeaders();
        public Dictionary<string, string> RequestHeaders { get; private set; }
        public bool IsNetworkError => requestHandler.isNetworkError;
        public bool IsHttpError => requestHandler.isHttpError;
        public bool IsSuccess => (!IsNetworkError && !IsHttpError) || IsRedirect;
        public HttpResponseBody Body { get; set; }
        public bool IsRedirect => !string.IsNullOrEmpty(GetRedirectLocation());
        public string Error { 
            get
            {
                return requestHandler.isNetworkError ? requestHandler.error: requestHandler.downloadHandler?.text;
            }
        }
        private UnityWebRequest requestHandler;
        private string requestBody;

        internal static HttpResponse Create(UnityWebRequest webRequest, Dictionary<string, string> requestHeaders, string requestBody = "")
        {
            return new HttpResponse
            {
                RequestHeaders = requestHeaders,
                requestHandler = webRequest,
                requestBody = requestBody,
                Body = new HttpResponseBody(webRequest),
            };
        }
        public string GetRedirectLocation()
        {
            // 如果状态码是 3xx 且包含 Location 字段，认为是重定向
            if (StatusCode >= 300 && StatusCode < 400 && Headers != null && Headers.ContainsKey("Location"))
            {
                return Headers["Location"];
            }
            return null;
        }

        public override string ToString() {
            string reqHeaderString = RequestHeaders == null 
            ? "" 
            : string.Join("\n", RequestHeaders.Select(kvp => $"{kvp.Key}: {kvp.Value ?? ""}"));
            string resHeaderString = Headers == null 
            ? "" 
            : string.Join("\n", Headers.Select(kvp => $"{kvp.Key}: {kvp.Value ?? ""}"));

            // 判断是否为重定向
            string responseBody = Body.ToText();
            
            return $@"REQUEST: {requestHandler?.url}
--headers:
{reqHeaderString}
--body:
{requestBody}

RESPONSE

--headers:
{resHeaderString}
--body:
{responseBody}
";
}
    }
}
