<commit_before>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Sc2StreamChatAssistant
{
    static class LadderManager
    {
        public class PlayerStats
        {
            [JsonProperty(PropertyName = "profile_path")]
            public string ProfilePath { get; set; }

            [JsonProperty(PropertyName = "race")]
            public string RaceString { get; set; }

            public Sc2Race Race
            {
                get { return Sc2RaceConverter.FromString(RaceString); }
            }

            public long Rating { get; set; }
            public long Wins { get; set; }
            public long Losses { get; set; }
            public long Points { get; set; }
        }

        public class PlayerStatsList
        {
            public List<PlayerStats> Results { get; set; }
        }

        //public async Task updateLadder(ulong ladderId, Predicate<Sc2LadderTeamData> filter)
        //{
        //    var request = new RestRequest("data/sc2/ladder/" + ladderId, Method.GET);
        //    request.AddQueryParameter("access_token", "3<PASSWORD>");
        //    fetchLadderHandler_ = Program.battleNetClient.ExecuteAsync(
        //        request, response => 
        //        {
        //            var ladderTeamData = JsonConvert.DeserializeObject<Sc2LadderData>(
        //                response.Content);

        //            ladderTeamData.team.ForEach(team =>
        //            {
        //                if (filter == null || filter(team))
        //                    team.member.ForEach(x => entries[
        //                        new LadderEntryId()
        //                        {
        //                            playerId = x.legacyLink.id,
        //                            ladderId = ladderId
        //                        }] = team);
        //            });

        //            DataUpdated?.Invoke(this);
        //        });
        //}

        //public async Task pullLadders(Sc2Character character)
        //{
        //    var request = new RestRequest(string.Format(@"sc2/profile/{0}/{1}/{2}/ladders",
        //        character.id, character.realm, character.displayName), Method.POST);
        //    var response =
        //        await Program.battleNetClient.ExecutePostTaskAsync<Sc2Character.LaddersList>(request);
        //    if (response.ResponseStatus == ResponseStatus.Completed)
        //    {
        //        character.ladders = response.Data;
        //    }
        //    // TODO
        //}

        public static async Task<Sc2LadderTeamData> FetchLadderTeamDataAsync(
            ulong ladderId, string profilePath, Sc2Race race)
        {
            var ladderData = await FetchLadderAsync(ladderId);
            return ladderData?.team?.Find(x => x.member.Exists(
                y =>
                {
                    return y.legacyLink != null && y.legacyLink.profilePath == profilePath
                        && y.Race == race;
                }));
        }

        public static async Task<Sc2LadderData> FetchLadderAsync(ulong ladderId)
        {
            return await NetworkHelper.FetchAsync<Sc2LadderData>(
                string.Format(@"{0}/data/sc2/ladder/{1}?access_token={2}",
                Program.battleNetUri, ladderId, Program.accessToken));
        }

        public static async Task<List<Sc2LadderId>> FetchLaddersAsync(string profilePath,
            string matchmakingQueue)
        {
            if (profilePath[0] != '/')
            {
                profilePath = "/" + profilePath;
            }

            var ladders = await NetworkHelper.FetchAsync<Sc2Character.LaddersList>(
                string.Format("{0}/sc2{1}/ladders?apikey={2}",
                    Program.battleNetUri, profilePath, Program.apiKey));

            var result = new List<Sc2LadderId>();

            ladders?.currentSeason.Select(x =>
                x.ladder != null && x.ladder.Count > 0
                && x.ladder[0].matchMakingQueue == matchmakingQueue
                ? x.ladder[0] : null).ToList().ForEach(
                x =>
                {
                    if (x != null)
                    {
                        result.Add(x);
                    }
                });

            return result;
        }

        public static async Task<PlayerStats> FetchPlayerStatsAsync(string displayName, Sc2Race race,
            long expectedMmr)
        {
            // Check if we know this player and have her full profile path
            var profile = Program.PlayerProfiles.Find(x => x.DisplayName == displayName);
            if (profile == null)
            {
                profile = Program.FriendsProfiles.Find(x => x.DisplayName == displayName);
            }
            if (profile != null)
            {
                Program.RecentSc2Region = profile.RegionCode;
                return await NetworkHelper.FetchAsync<PlayerStats>(
                    Program.ServerUri + $"/data/{profile.RegionCode}/{profile.Id}/{profile.Realm}/"
                        + $"{profile.DisplayName}/mmr/{race}");
            }
            // Try to find player using only her display name
            // Look up in the most recent used sc2 region
            var playersList = await NetworkHelper.FetchAsync<PlayerStatsList>(
                Program.ServerUri + $"/data/{Program.RecentSc2Region}/lookup/{displayName}/{race}");
            return playersList?.Results?.OrderBy(x => Math.Abs(x.Rating - expectedMmr)).FirstOrDefault();
        }

        public static async Task<long?> FetchPlayerMmrAsync(string profilePath,
            string matchmakingQueue, Sc2Race race)
        {
            var laddersSolo = await FetchLaddersAsync(
                profilePath, matchmakingQueue);

            foreach (var ladderId in laddersSolo)
            {
                // TODO
                var ladderData = await LadderManager.FetchLadderTeamDataAsync(
                    ladderId.ladderId, profilePath, race);
                if (ladderData != null)
                {
                    return ladderData.rating;
                }
            }

            return null;
        }
    }<commit_msg>Clean up LadderManager class<commit_after>﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sc2StreamChatAssistant
{
    static class LadderManager
    {
        public class PlayerStats
        {
            [JsonProperty(PropertyName = "profile_path")]
            public string ProfilePath { get; set; }

            [JsonProperty(PropertyName = "race")]
            public string RaceString { get; set; }

            public Sc2Race Race
            {
                get { return Sc2RaceConverter.FromString(RaceString); }
            }

            public long Rating { get; set; }
            public long Wins { get; set; }
            public long Losses { get; set; }
            public long Points { get; set; }
        }

        public class PlayerStatsList
        {
            public List<PlayerStats> Results { get; set; }
        }

        public static async Task<PlayerStats> FetchPlayerStatsAsync(string displayName, Sc2Race race,
            long expectedMmr)
        {
            // Check if we know this player and have her full profile path
            var profile = Program.PlayerProfiles.Find(x => x.DisplayName == displayName);
            if (profile == null)
            {
                profile = Program.FriendsProfiles.Find(x => x.DisplayName == displayName);
            }
            if (profile != null)
            {
                Program.RecentSc2Region = profile.RegionCode;
                return await NetworkHelper.FetchAsync<PlayerStats>(
                    Program.ServerUri + $"/data/{profile.RegionCode}/{profile.Id}/{profile.Realm}/"
                        + $"{profile.DisplayName}/mmr/{race}");
            }
            // Try to find player using only her display name
            // Look up in the most recent used sc2 region
            var playersList = await NetworkHelper.FetchAsync<PlayerStatsList>(
                Program.ServerUri + $"/data/{Program.RecentSc2Region}/lookup/{displayName}/{race}");
            return playersList?.Results?.OrderBy(x => Math.Abs(x.Rating - expectedMmr)).FirstOrDefault();
        }
    }
{'fraction_non_alphanumeric': 0.1004739336492891, 'fraction_numerical': 0.005213270142180095, 'mean_word_length': 1.540939193257074, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6838620', 'n_tokens_mistral': 2217, 'n_tokens_neox': 2109, 'n_words': 459}