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

public class StorageManager : MonoBehaviour
{
    public static StorageManager Instance;

    public CameraManager cameraManager;
    private StorageReference storage;
    private DatabaseReference realtimeDB;

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

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

    public void DeleteFileOfRoom(Room _room, Action callBack_OnFinish)
    {
        List<Task> deleteTasks = new List<Task>();
        foreach(Player player in _room.players.Values.ToList())
        {
            foreach(Proposition proposition in _room.GetPropositionsForPlayer(player))
            {
                if (proposition != null)
                {
                    if(proposition.photoUrl != null)
                    {
                        Debug.Log($"Adding a task to delete {proposition.photoUrl}", this);
                        deleteTasks.Add(Task.Run(async () =>
                        {
                            string temp = proposition.photoUrl;
                            StorageReference imageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(temp);
                            Debug.Log($"deleting {temp}", this);
                            await imageRef.DeleteAsync();
                        }));
                    }
                }
            }
        }
        if(deleteTasks.Count > 0)
        {
            RunDeleteTasks(deleteTasks, callBack_OnFinish);
        }
        else
        {
            Debug.Log($"There is no files to delete for room {_room.code}", this);
            callBack_OnFinish.Invoke();
        }
    }

    private void RunDeleteTasks(List<Task> deleteTasks, Action callback_OnFinish)
    {
        int taskCount = deleteTasks.Count;
        Debug.Log($"There are {taskCount} files to delete", this);

        Task.WhenAll(deleteTasks).ContinueWithOnMainThread(_ =>
        {
            Debug.Log($"all delete tasks are done", this);
            callback_OnFinish?.Invoke();
        });
    }

    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());
            }
        });

    }
}
