using System;
using System.Collections.Generic;
using Firebase.Extensions;
using Firebase.Firestore;
using UnityEngine;
using UnityEngine.UI;

public class CharacterSelection : MonoBehaviour
{

    [SerializeField] public static string selectedCharJson = "";
    public List<CharacterDataSO> predefinedCharacterJsons;
    public List<Button> predefinedCharacterButtons;

    public static Action OnCharacterChanged;


    void Start()
    {
        for (int i = 0; i < predefinedCharacterButtons.Count; i++)
        {
            int tempI = i;
            predefinedCharacterButtons[i].onClick.AddListener(() => { OnPredefinedCharButtonPress(tempI); });
        }
        LoadCharacterSkinCloud();
    }

    public void LoadCharacterFromString(string characterData)
    {
        selectedCharJson = characterData;
        OnCharacterChanged?.Invoke();
    }

    void OnPredefinedCharButtonPress(int i)
    {
        selectedCharJson = predefinedCharacterJsons[i].jsonCharData;
        OnCharacterChanged?.Invoke();
        SaveCharacterSkinCloud();
    }

    public static void SaveCharacterSkinCloud()
    {
#if UNITY_EDITOR
        PlayerPrefs.SetString("skinData", selectedCharJson);
        PlayerPrefs.Save();
#else
        FirebaseFirestore db = FirebaseFirestore.DefaultInstance;

        Dictionary<string,object> skindataDictionary = new Dictionary<string, object>();
        skindataDictionary.Add("json", selectedCharJson);

        DocumentReference docRef = db.Collection("SkinData").Document(gplayAuth.userID);
            docRef.SetAsync(skindataDictionary).ContinueWithOnMainThread(task => {
                if(task.IsCompleted){
                    Debug.Log("**** Save Completed Firestore ****");
                }
                else{
                    Debug.Log("**** Failed to save data to firestore ****");
                }
            });

#endif

    }

    void LoadCharacterSkinCloud()
    {
#if UNITY_EDITOR
        if (PlayerPrefs.HasKey("skinData"))
        {
            LoadCharacterFromString(PlayerPrefs.GetString("skinData"));
        }

#else

        FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
        DocumentReference docRef = db.Collection("SkinData").Document(gplayAuth.userID);
            docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
                DocumentSnapshot snapshot = task.Result;
                if(snapshot.Exists){
                    
                    LoadCharacterFromString(snapshot.GetValue<string>("json"));
                    
                }else{
                    //show error previous data doesnt exists to load 
                    Debug.Log("**** No previous data to load ****");

                }
            });

#endif

    }
}