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

namespace TFramework
{
    public class NetHelper
    {
        private int m_timeOut = 20;

        /// <summary>
        /// 请求最大等待时长
        /// </summary>
        /// <param name="timeOut"></param>
        public NetHelper(int timeOut)
        {
            m_timeOut = timeOut;
        }

        public NetHelper() { }

        public async UniTask<CallBackArgs> Get(string url, params Header[] headers)
        {
            UnityWebRequest get = UnityWebRequest.Get(url);
            foreach (var item in headers)
            {
                get.SetRequestHeader(item.m_headerKey, item.m_headerValue);
            }
            get.timeout = m_timeOut;
            try
            {
                await get.SendWebRequest();
            }
            catch (Exception e)
            {
                return ErrorCallBack(e.Message);
            }
            return OverCallBack(get);
        }

        public async UniTask<CallBackArgs> Post(string url, string json, params Header[] headers)
        {
            using (UnityWebRequest request = new UnityWebRequest(url, "POST"))
            {
                request.uploadHandler = new UploadHandlerRaw(Encoding.Default.GetBytes(json));
                request.downloadHandler = new DownloadHandlerBuffer();
                foreach (var item in headers)
                {
                    request.SetRequestHeader(item.m_headerKey, item.m_headerValue);
                }
                request.timeout = m_timeOut;

                try
                {
                    await request.SendWebRequest();
                }catch(Exception e)
                {
                    return ErrorCallBack(e.Message);
                }

                return OverCallBack(request);
            }
        }

        public async UniTask<CallBackArgs> Post(string url, WWWForm form, params Header[] headers)
        {
            using (UnityWebRequest request = UnityWebRequest.Post(url, form))
            {
                foreach (var item in headers)
                {
                    request.SetRequestHeader(item.m_headerKey, item.m_headerValue);
                }
                request.timeout = m_timeOut;

                try
                {
                    await request.SendWebRequest();
                }
                catch (Exception e)
                {
                    return ErrorCallBack(e.Message);
                }

                return OverCallBack(request);
            }
        }

        private CallBackArgs OverCallBack(UnityWebRequest request)
        {
            CallBackArgs m_callBackArgs = new CallBackArgs();
            m_callBackArgs.IsError = request.result == UnityWebRequest.Result.ProtocolError
                    || request.result == UnityWebRequest.Result.ConnectionError
                    || request.result == UnityWebRequest.Result.DataProcessingError || !string.IsNullOrEmpty(request.error);

            m_callBackArgs.Error = request.error;
            m_callBackArgs.Text = request.downloadHandler.text;
            m_callBackArgs.Data = request.downloadHandler.data;
            return m_callBackArgs;
        }

        private CallBackArgs ErrorCallBack(string error)
        {
            CallBackArgs m_callBackArgs = new CallBackArgs();
            m_callBackArgs.IsError = true;
            m_callBackArgs.Error = error;
            return m_callBackArgs;
        }
    }


    /// <summary>
    /// Web请求回调
    /// </summary>
    public class CallBackArgs : EventArgs
    {
        public bool IsError;
        public string Text;
        public string Error;
        public byte[] Data;

        public void Reset()
        {
            IsError = false;
            Text = string.Empty;
            Error = string.Empty;
            Data = null;
        }
    }

    public struct Header
    {
        public string m_headerKey;
        public string m_headerValue;

        public Header(string headerKey, string headerValue)
        {
            m_headerKey = headerKey;
            m_headerValue = headerValue;
        }

        public static Header DefaultJsonHeader = new Header("Content-Type", "application/json");
    }
}