using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine.Networking;

namespace Plugins.JNGame.Util
{
    
    public class JAPIConfig{
        public string BaseURL = "http://localhost:8080"; //baseURL 默认HTTP头
        public int Timeout = 5000; //超时时间
    }
    
    public class JAPIData<T>{
        public T Data;
    }
    
    /**
     * JNGame 的 网络请求类
     */
    public class JAPI {
        
        private JAPIConfig _config;
        
        public JAPI(JAPIConfig config = null)
        {
            if (config == null) config = new JAPIConfig();
            this._config = config;
        }

        public async UniTask<T> Get<T>(string url)
        {
            var request = UnityWebRequest.Get($"{this._config.BaseURL}/{url}");
            return JsonConvert.DeserializeObject<T>((await request.SendWebRequest()).downloadHandler.text);
        }

        public async UniTask<T> Post<T>(string url,Dictionary<string,string> data)
        {
            var request = UnityWebRequest.Post($"{this._config.BaseURL}/{url}",data);
            return JsonConvert.DeserializeObject<T>((await request.SendWebRequest()).downloadHandler.text);
        }
        
        public async UniTask<T> Post<T,TA>(string url,TA data)
        {
            var request = UnityWebRequest.Post($"{this._config.BaseURL}/{url}",JsonConvert.SerializeObject(data));
            return JsonConvert.DeserializeObject<T>((await request.SendWebRequest()).downloadHandler.text);
        }
        
        public async UniTask<byte[]> GetByte(string url)
        {
            var request = UnityWebRequest.Get($"{this._config.BaseURL}/{url}");
            return (await request.SendWebRequest()).downloadHandler.data;
        }
        
        public async UniTask<byte[]> PostByte(string url,Dictionary<string,string> data)
        {
            var request = UnityWebRequest.Post($"{this._config.BaseURL}/{url}",data);
            return (await request.SendWebRequest()).downloadHandler.data;
        }
        
    }
}