using PlayFab.ClientModels;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using PlayFab;
using UnityEngine;

public class PlayFabTool
{
    public class PFPlayerInfo
    {
        public string DisplayName { get; set; }
        public string Avatar { get; set; }
        public int SdkId { get; set; }
        public string PlayFabId { get; set; }
        public int Level { get; set; }
        public int Diamond { get; set; }
        public int Energy { get; set; }

        public static PFPlayerInfo Empty(int sdkId)
        {
            return new PFPlayerInfo()
            {
                DisplayName = "Unknown",
                SdkId = sdkId,
                PlayFabId = string.Empty,
                Level = 0,
                Diamond = 0,
                Energy = 0
            };
        }

        public override string ToString()
        {
            return JObject.FromObject(this).ToString();
        }
    }
    
    public static async Task<PFPlayerInfo> GetPFPlayerInfoBySDKId(int sdkId, string playfabTitleId)
    {
        PlayFab.Internal.PlayFabWebRequest.SkipCertificateValidation();
        var tcs = new TaskCompletionSource<PFPlayerInfo>();
        var settings = new PlayFabApiSettings() { TitleId = playfabTitleId };
        var pfClient = new PlayFabClientInstanceAPI(settings);

        var requestParams = new GetPlayerCombinedInfoRequestParams()
        {
            GetPlayerProfile = true,
            GetUserData = true,
            ProfileConstraints = new PlayerProfileViewConstraints()
            {
                ShowDisplayName = true,
                ShowAvatarUrl = true,
            },
            UserDataKeys = new List<string>() { "NewPlayerDataDic" }
        };

        var request = new LoginWithCustomIDRequest()
        {
            CreateAccount = false,
            CustomId = sdkId.ToString(),
            InfoRequestParameters = requestParams
        };

        pfClient.LoginWithCustomID(request,
            (result) =>
            { var infoResultPayload = result.InfoResultPayload;

                if(!infoResultPayload.UserData.TryGetValue("NewPlayerDataDic", out var userData))
                {
                    tcs.SetResult(PFPlayerInfo.Empty(sdkId));
                    return;
                }
                var playerProfile = infoResultPayload.PlayerProfile;
                var displayName = playerProfile.DisplayName;
                var avatar = playerProfile.AvatarUrl;
                var playfabId = result.PlayFabId;

                JObject userDataJson = JObject.Parse(userData.Value);
                if(!userDataJson.TryGetValue("newData", out var newData))
                {
                    tcs.SetResult(PFPlayerInfo.Empty(sdkId));
                    return;
                }
                var dataList = newData.ToString().Split(',');
                var level = int.Parse(dataList[0]);
                var energy = int.Parse(dataList[3]);
                var diamond = int.Parse(dataList[11]);
                var pfPlayerInfo = new PFPlayerInfo(){
                    DisplayName = displayName,
                    Avatar = avatar,
                    SdkId = sdkId,
                    PlayFabId = playfabId,
                    Level = level,
                    Diamond = diamond,
                    Energy = energy
                };
                tcs.SetResult(pfPlayerInfo);
            },
        (error) =>
        {
            Debug.LogWarning(error.ErrorMessage);
            tcs.SetResult(null);
        });
        return await tcs.Task;
    }
}
