using Firebase.Database;
using Firebase.Extensions;
using Firebase.Storage;
using System;
using System.Collections;
using System.Security.Policy;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;

public class StorageManager : MonoBehaviour
{
    public CameraManager cameraManager;
    private StorageReference storage;
    private DatabaseReference realtimeDB;

    void Awake()
    {
        FirebaseInitializer.Instance.onFirebaseReady += Initialize;
    }

    void Initialize()
    {
        FirebaseInitializer.Instance.onFirebaseReady -= Initialize;
        storage = FirebaseStorage.DefaultInstance.RootReference;
        realtimeDB = FirebaseDatabase.DefaultInstance.RootReference;
    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void UploadPhoto(string roomCode, string playerId, int question, int proposition, Action<bool> callback_OnPhotoUploaded)
    {
        Texture2D photo = cameraManager.GetPhoto();
        byte[] photoBytes = ImageConversion.EncodeToJPG(photo);
        string imageUuid = Guid.NewGuid().ToString();

        string root = "gs://ggj2024-5cb41.appspot.com/";
        string path = $"{roomCode}/{playerId}/{imageUuid}.png";
        StorageReference imageRef = storage.Child(path);

        imageRef.PutBytesAsync(photoBytes).ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted || task.IsCanceled)
            {
                callback_OnPhotoUploaded?.Invoke(false);
                Debug.LogException(task.Exception);
                // Uh-oh, an error occurred!
            }
            else
            {
                callback_OnPhotoUploaded?.Invoke(true);
                realtimeDB
                    .Child("rooms")
                    .Child(roomCode)
                    .Child("questions")
                    .Child(question.ToString())
                    .Child("propositions")
                    .Child(proposition.ToString())
                    .Child("photoUrl")
                    .SetValueAsync(root + path);
            }
        });
    }

    public static IEnumerator DownloadImage_Coroutine(string _url, Action<Texture> callback_OnTextureDownloaded)
    {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(_url);
        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(request.error);
        }
        else
        {
            callback_OnTextureDownloaded?.Invoke(((DownloadHandlerTexture)request.downloadHandler).texture);
        }
    }

    public static void ConvertGoogleStorageURLToHttpsUrl(string _gsURL, Action<string> callback_OnURLFound)
    {
        StorageReference imageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(_gsURL);
        imageRef.GetDownloadUrlAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.LogException(task.Exception);
            }
            else
            {
                //Debug.Log("Image HTTPS URL: " + task.Result);
                callback_OnURLFound?.Invoke(task.Result.ToString());
            }
        });

    }
}
