using Game.Network;
using Game.Network.DTO;
using Newtonsoft.Json;
using System;
using UnityEngine;
using UnityEngine.Networking;

public class NetworkManager : MonoBehaviour
{
    public static NetworkManager Instance;

    //private string _baseGameDBUrl = "https://localhost:7134/myGame";
    private string _baseGameDBUrlHttp = "http://152.69.235.249:5000/myGame";

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this; //만들어진 자신을 인스턴스로 설정
        }
        else
        {
            Destroy(gameObject); //이미 인스턴스가 있으면 자신을 파괴
        }
    }

    public async Awaitable<T> GetDatabaseData<T>(string endPoint)
    {
        string url = $"{_baseGameDBUrlHttp}/{endPoint}";
        using UnityWebRequest request = UnityWebRequest.Get(url); //앞의 using은 사용이 끝난(메서드 종료) 외부 리소스 객체들을 알아서 지워주도록 설정하는 예약어이다
        request.certificateHandler = new BypassCertificate();

        try
        {
            await request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                string json = request.downloadHandler.text;

                ApiResponse<T> container = JsonConvert.DeserializeObject<ApiResponse<T>>(json);
                Debug.Log($"응답 : data = {container.data}, count = {container.count}, message = {container.message}");

                return container.data;
            }
        }
        catch (Exception e)
        {
            Debug.LogException(e);
        }
        return default;
    }
}
