using UnityEngine;
using BestHTTP;
using System;
using Newtonsoft.Json;


public class NetworkManager : SingletonMonoBehaviour<NetworkManager>
{
    [SerializeField] private string baseUrl;

    /// <summary>
    /// 데이터를 송수신해야할 때 사용합니다. send()는 생성을 마치고 자동으로 보냅니다.
    /// </summary>
    /// <typeparam name="T">역직렬화할 타입</typeparam>
    /// <param name="API">api 주소</param>
    /// <param name="onRequestFinished">데이터 받은 후 처리할 절차</param>
    /// <param name="serializeData">전송할 데이터, null로 넣으면 안보냅니다.</param>
    /// <param name="methods">동작방식</param>
    /// <returns>역직렬화된 데이터 or 기본값(반환 받지 못함)</returns>
    public HTTPRequest CreateRequest<T>(string api, object serializeData, Action<T> onSuccess, Action<T> onFail = null, HTTPMethods methods = HTTPMethods.Post)
    {
        string url = $"{baseUrl}{api}".Replace("\\p{Z}", String.Empty);

        var httpRquest = new HTTPRequest(new Uri(url) //url 넣기
            , methods //동작 방식 넣기
            , (request, response) => {
                if (response == null || (response.StatusCode != 200))
                {
                    onFail?.Invoke(default(T));
                }
                else
                {
                    T deSerialized = JsonConvert.DeserializeObject<T>(response.DataAsText);
                    onSuccess?.Invoke(deSerialized);
                }
            });

        if (serializeData != null)
        {
            httpRquest.SetHeader("Content-Type", "application/json; charset=UTF-8");
            string json = JsonConvert.SerializeObject(serializeData);
            httpRquest.RawData = System.Text.Encoding.UTF8.GetBytes(json);
        }

        httpRquest.Send();
        return httpRquest;
    }
    public HTTPRequest CreateImageRequest(string api, object serializeData, Action<Texture2D> onSuccess, Action<Texture2D> onFail = null, HTTPMethods methods = HTTPMethods.Post)
    {
        string url = $"{baseUrl}{api}".Replace("\\p{Z}", String.Empty);

        var httpRquest = new HTTPRequest(new Uri(url) //url 넣기
            , methods //동작 방식 넣기
            , (request, response) => {
                if (response == null || (response.StatusCode != 200))
                {
                    onFail?.Invoke(null);
                }
                else
                {
                    Texture2D deSerialized = response.DataAsTexture2D;
                    onSuccess?.Invoke(deSerialized);
                }
            });

        if (serializeData != null)
        {
            httpRquest.SetHeader("Content-Type", "application/json; charset=UTF-8");
            string json = JsonConvert.SerializeObject(serializeData);
            httpRquest.RawData = System.Text.Encoding.UTF8.GetBytes(json);
        }

        httpRquest.Send();
        return httpRquest;
    }
}
