using Cysharp.Threading.Tasks;
using Darkmatter.Core;
using System.Collections.Generic;
using System.Threading.Tasks;
using Unity.Services.Leaderboards;
using UnityEngine;
using VContainer;


namespace Darkmatter.Presentation
{
    public class LeaderBoardController : ILeaderBoardController
    {
        private const string leaderBoardID = "helix_leaderboard";
        private LeaderBoardView leaderBoardView;


        private List<LeaderBoardData> activeLBData = new List<LeaderBoardData>();
        [Inject] IPool<LeaderBoardData> leaderBoardDataPool;

        public LeaderBoardController( LeaderBoardView _leaderBoardView )
        {
            this.leaderBoardView = _leaderBoardView;
            leaderBoardView.ExitButton.onClick.AddListener(OnExitBtnClicked);
        }

        private void OnExitBtnClicked()
        {
            foreach(var lbData in activeLBData)
            {
                lbData.ResetData();
                leaderBoardDataPool.ReturnToPool(lbData);
            }
            activeLBData.Clear();
            leaderBoardView.Hide();
        }

        public async UniTask ShowLeaderBoardAsync()
        {
            leaderBoardView.Show();
            leaderBoardView.ShowLoading(true);
            await LoadLeaderBoard();
            leaderBoardView.ShowLoading(false);
            
        }

        async UniTask LoadLeaderBoard()
        {
            var score = await LeaderboardsService.Instance.GetScoresAsync(leaderBoardID, new GetScoresOptions { Limit = 10 });
            int rank = 1;
            foreach(var entry in score.Results)
            {
                LeaderBoardData LBData = leaderBoardDataPool.GetFromPool();

                string playerID = PlayerPrefs.GetString("PlayerID");

                if (entry.PlayerId == playerID)
                {
                    LBData.BackgroundPanel.color = Color.yellow;
                    LBData.playerName.text = "You";
                }
                else LBData.playerName.text = entry.PlayerName;
                
                LBData.playerPos.text = rank.ToString();
                LBData.playerScore.text = entry.Score.ToString();
                activeLBData.Add(LBData); //adds the active data to the list
                rank++;
            }
        }

        public async UniTask UpdateLeaderBoardScore(int score)
        {
            await LeaderboardsService.Instance.AddPlayerScoreAsync(leaderBoardID, score);
        }

        public void HideLeaderBoard()
        {
            leaderBoardView.Hide();
        }
    }
}
