using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class WaitForPropositionsPage : MonoBehaviour
{
    public TextMeshProUGUI propositionCounter;
    public float propositionTime = 60;
    public List<TextMeshProUGUI> playerLabels = new List<TextMeshProUGUI>();

    private DateTime endOfPropositionDate = DateTime.MinValue;
    private bool allPlayersHasProposedTwoPictures = false;

    private event Action OnPropositionFinish;
    private Room myRoom;

    private List<string> playersIdWhoHaveProposed = new List<string>();

    public void Initialize(Room _myRoom, Action _onPropositionFinish)
    {
        endOfPropositionDate = DateTime.Now.AddSeconds(propositionTime);
        gameObject.SetActive(true);
        OnPropositionFinish = _onPropositionFinish;
        myRoom = _myRoom;
        allPlayersHasProposedTwoPictures = false;
        playersIdWhoHaveProposed.Clear();
        foreach(TextMeshProUGUI label in playerLabels)
        {
            label.color = Color.white;
        }

        ShowPlayerLabels();
    }

    public void OnRoomUpdate(Room _myRoom)
    {
        myRoom = _myRoom;
    }


    // Update is called once per frame
    void Update()
    {
        //while MakeProposition State
        if (endOfPropositionDate != DateTime.MinValue)
        {
            TimeSpan duration = endOfPropositionDate - DateTime.Now;


            if (duration.TotalMilliseconds <= 0 || allPlayersHasProposedTwoPictures)
            {
                OnPropositionFinish?.Invoke();
                OnPropositionFinish = null;
                gameObject.SetActive(false);
                return;
            }

            CheckPlayersWhoHaveProposed();
            propositionCounter.text = ((int)duration.TotalSeconds).ToString("D1");
        }
    }
    private void ShowPlayerLabels()
    {
        //display only correct numbers of labels and set names
        List<Player> players = myRoom.GetOrderedPlayerList();
        for (int i = 0; i < playerLabels.Count; i++)
        {
            if (i < players.Count)
            {
                playerLabels[i].gameObject.SetActive(true);
                playerLabels[i].text = players[i].name;
            }
            else
            {
                playerLabels[i].gameObject.SetActive(false);
            }
            //Debug.Log($"toggling {playerLabels[i].gameObject.name} accordingly to its player connection");
        }
    }

    private void CheckPlayersWhoHaveProposed()
    {
        foreach (Player player in myRoom.GetPlayerList())
        {
            if (playersIdWhoHaveProposed.Contains(player.id))
                continue;

            bool playerHasAnsweredBothProposition = true;
            Proposition[] propositions = myRoom.GetPropositionsForPlayer(player).ToArray();
            //Debug.Log($"I found {propositions.Length} propositions for {player.name}", this);

            if (propositions.Length < 2)
                playerHasAnsweredBothProposition = false;
            else
            {
                for (int i = 0; i < propositions.Length; i++)
                {
                    if (string.IsNullOrEmpty(propositions[i].photoUrl))
                    {
                        //Debug.Log($"{player.name}'s proposition {i} has no photoURL", this);
                        playerHasAnsweredBothProposition = false;
                    }
                }
            }

            if (playerHasAnsweredBothProposition)
            {
                Debug.Log($"{player.name}'s has answered both propositions !", this);
                playerLabels.Find(x => x.text == player.name).color = Color.green;
                playersIdWhoHaveProposed.Add(player.id);
            }
            //Debug.Log($"{playersIdWhoHaveProposed.Count}/{myRoom.players.Count} players have answered.", this);
            if(playersIdWhoHaveProposed.Count == myRoom.players.Count)
            {
                allPlayersHasProposedTwoPictures = true;
            }
        }

    }
}
