using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;

using System.Collections.Generic;
using Newtonsoft.Json;

/// <summary>
/// 异步封装unityWebRequest请求
/// </summary>
public static class AsyncWebReq
{
    public static async UniTask<T> Get<T>(string endpoint)
    {
        var getRequest = CreateRequest(endpoint);
        await getRequest.SendWebRequest();
#if UNITY_EDITOR
        Debug.Log("async Get req : " + getRequest.downloadHandler.text);
#endif
        T result = JsonUtility.FromJson<T>(getRequest.downloadHandler.text);
        getRequest.Dispose();
        return result;
    }


    public static async UniTask<T> Post<T>(string endpoint, object payload)
    {
        var postRequest = CreateRequest(endpoint, RequestType.POST, payload);
        await postRequest.SendWebRequest();
#if UNITY_EDITOR
        Debug.Log("async Post req : " + postRequest.downloadHandler.text);
        Debug.Log("endpoint : " + endpoint);
#endif
        T result = JsonUtility.FromJson<T>(postRequest.downloadHandler.text);
        postRequest.Dispose();
        return result;
    }

    public static UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
    {
        var request = new UnityWebRequest(path, type.ToString());
        if (data != null)
        {
            string reqJson = JsonConvert.SerializeObject(data);
#if UNITY_EDITOR
            Debug.Log($"async req json : {reqJson}");
#endif
            var bodyRaw = Encoding.UTF8.GetBytes(reqJson);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        }

        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        return request;
    }

    private static void AttachHeader(UnityWebRequest request, string key, string value)
    {
        request.SetRequestHeader(key, value);
    }
   
    /// <summary>
    /// 请求类型
    /// </summary>
    public enum RequestType
    {
        GET = 0,
        POST = 1
    }
}