using Game.Network.DTO;
using Newtonsoft.Json;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TextCore.Text;

public class DataManager : MonoBehaviour
{
    public static DataManager Instance;

    //내 캐릭터들
    public List<UserCharacter> MyCharacters = new List<UserCharacter>();

    //모든 캐릭터들 데이터(적,NPC,플레이어블)

    public Dictionary<string, PlayableCharacter> PlayableCharacterData = new Dictionary<string, PlayableCharacter>();
    public Dictionary<string, EnemyCharacter> EnemyCharacterData = new Dictionary<string, EnemyCharacter>();
    public Dictionary<string, NpcCharacter> NpcCharacterData = new Dictionary<string, NpcCharacter>();

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

    private async Awaitable Start()
    {

        await LoadUserCharacters(1);
        await LoadPlayableCharacters();
    }

    public async Awaitable LoadUserCharacters(int userNo)
    {
        UserCharacterDTO[] characterDTOs = await NetworkManager.Instance.GetDatabaseData<UserCharacterDTO[]>($"userCharacters/{userNo}");

        if (characterDTOs != null)
        {
            MyCharacters.Clear();

            foreach ( UserCharacterDTO characterDTO in characterDTOs )
            {
                UserCharacter uc = new UserCharacter();
                uc.UserCharacterNo = characterDTO.userCharacterNo;
                uc.UserNo = characterDTO.userNo;
                uc.CharacterCode = characterDTO.characterCode;
                uc.Lv = characterDTO.lv;
                uc.StrStat = characterDTO.strStat;
                uc.IntStat = characterDTO.intStat;
                uc.MaxHp = characterDTO.maxHp;
                uc.MaxMp = characterDTO.maxMp;
                uc.DefaultControl = characterDTO.defaultControl;

                MyCharacters.Add(uc);
            }
        }
        else
        {
            Debug.LogError("캐릭터 데이터를 불러오지 못했습니다.");
        }
    }

    public async Awaitable LoadPlayableCharacters()
    {
        PlayableCharacterDTO[] characterDTOs = await NetworkManager.Instance.GetDatabaseData<PlayableCharacterDTO[]>($"playableCharacters");

        if (characterDTOs != null)
        {
            PlayableCharacterData.Clear();

            foreach (PlayableCharacterDTO characterDTO in characterDTOs)
            {
                PlayableCharacter c = new PlayableCharacter();
                c.CharacterCode = characterDTO.characterCode;
                c.CharacterType = characterDTO.characterType;

                PlayableCharacterData.TryAdd(c.CharacterCode, c);
            }
        }
        else
        {
            Debug.LogError("캐릭터 데이터를 불러오지 못했습니다.");
        }
    }
}
