using QwirkleClassLibrary.Players;
using QwirkleClassLibrary.Games;
using QwirkleClassLibrary.Boards;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace Qwirkle.Views
{
    public partial class Scoreboard : ContentView
    {
        private Game game = ((App)Application.Current!).Game;

        private ObservableCollection<KeyValuePair<string, int>>? scoreboardList;
        public ObservableCollection<KeyValuePair<string, int>>? ScoreboardList
        {
            get => scoreboardList;
            set
            {
                if (scoreboardList != value)
                {
                    scoreboardList = value;
                    OnPropertyChanged(nameof(ScoreboardList));
                }
            }
        }
        public Scoreboard()
        {
            InitializeComponent();
            BindingContext = this;


            UpdateScoreboard();

            game.PropertyChanged += OnScoreChanged;
        }

        private void UpdateScoreboard()
        {
            var scoreboard = game.ObservableScoreBoard.OrderByDescending(x => x.Value).ThenBy(x => x.Key);
            ScoreboardList = new ObservableCollection<KeyValuePair<string, int>>(scoreboard);
        }

        private void OnScoreChanged(object? sender, EventArgs e)
        {
            UpdateScoreboard();
        }
    }
}
