using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Firebase.Extensions;
using Firebase.Storage;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class PropositionFrame : MonoBehaviour
{
    public RawImage picture;
    public GameObject voterStickerPrefab;
    public TextMeshProUGUI playerName;
    public Transform playerGrid;
    public Texture2D defaultTexture;

    private Dictionary<Player, GameObject> currentVoters = new Dictionary<Player, GameObject>();
    private Proposition proposition;

    private void OnEnable()
    {
        picture.texture = defaultTexture;
    }

    public void SetProposition(Proposition _proposition)
    {
        Debug.Log($"Initializing {_proposition.owner.name}'s proposition", this);
        proposition = _proposition;
        playerName.text = proposition.owner.name;

        if (!string.IsNullOrEmpty(proposition.photoUrl))
            DisplayPicture(proposition.photoUrl);
        else
            picture.texture = defaultTexture;

        ResetVoters();
    }

    public void SetNoProposition()
    {
        picture.texture = defaultTexture;
        playerName.text = "Nobody";
        ResetVoters();
    }

    private void ResetVoters()
    {
        foreach (var voters in currentVoters)
        {
            Destroy(voters.Value);
        }
        currentVoters.Clear();

    }

    /// <summary>
    /// Url is Google bucket URL. We 
    /// </summary>
    /// <param name="_gsUrl"></param>
    private void DisplayPicture(string _gsUrl)
    {
        //Debug.Log($"Google Storage URL : {_gsUrl}");
        StorageManager.ConvertGoogleStorageURLToHttpsUrl(_gsUrl, _url =>
        {
            StartCoroutine(StorageManager.DownloadImage_Coroutine(_url, _texture =>
            {
                //Debug.Log("Set texture in the raw image");
                picture.texture = _texture;
            }));
        });
    }

    public void UpdateVoters(List<Player> _newVoters)
    {
        //Debug.Log($"There are some new voters for {proposition.owner}'s proposition", this);
        foreach (Player p in _newVoters)
        {
            if (!currentVoters.Keys.Contains(p))
            {
                PlayerSticker sticker = Instantiate(voterStickerPrefab, playerGrid).GetComponent<PlayerSticker>();
                sticker.Initialize(p.name, RoomManager.Instance.myRoom.GetPlayerOrder(p));
                currentVoters.Add(p, sticker.gameObject);
                Debug.Log($"{p.name} has just voted for {proposition.owner.name}'s proposition.");
            }
        }
    }
}
