using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ScoringPage : MonoBehaviour
{
    [SerializeField] private List<PlayerSticker> playerStickers;

    private Dictionary<string,int> scoreByUser = new Dictionary<string,int>();

    private void Awake()
    {
        if(playerStickers == null || playerStickers.Count == 0)
        {
            Debug.LogError("You must provide the player stickers to the Scoring Page", this);
        }
    }

    public void Initialize(Room _room)
    {
        AudioManager.Instance.ChangeMusic(MusicTitle.Ending);
        gameObject.SetActive(true);
        foreach(PlayerSticker p in playerStickers)
        {
            p.gameObject.SetActive(false);
        }

        gameObject.SetActive(true);
        Player[] players = _room.GetOrderedPlayerList().ToArray();

        foreach (var player in players)
        {
            scoreByUser[player.id] = 0;
            getPlayerScore(_room, player);
        }
        var sortedList = scoreByUser.ToList();

        scoreByUser = scoreByUser.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        List<string> playersId = scoreByUser.Keys.ToList();
        int countPlayers = scoreByUser.Keys.ToList().Count;
        for (int i = 0; i < countPlayers; i++)
        {
            Player p = _room.GetPlayerById(scoreByUser.Keys.ToList()[i]);
            playerStickers[i].gameObject.SetActive(true);
            string nameAndScore = p.name +'\n'+ scoreByUser[p.id] +" pts";
            playerStickers[i].Initialize(nameAndScore, i);
        }
    }

    public void getPlayerScore(Room _room, Player _player)
    {
        List<Proposition> propostitions = _room.GetPropositionsForPlayer(_player);
        propostitions.ForEach(p =>
        {
            
            if(p.voters != null)
            {
                scoreByUser[_player.id] += p.voters.Count;
            }
        });
        Debug.Log(_player.name);
        Debug.Log(scoreByUser[_player.id]);

    }
}
