﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PlayFab;

namespace Onward.CustomContent.EditorTools
{
    /// <summary>
    /// Helper class to make this callback hell a bit more nice and easier to query within the UI
    /// </summary>
    public class PlayFabUploadHelper
    {
        static readonly string TitleId      = "DFF0F";
        static readonly string UgcItemsKey  = "ugc_items";

        public delegate void DelPlayFabError(string message);
        public delegate void DelPlayFabSuccess();
        public delegate void DelRepaint();
        public delegate void DelPublishSuccess(string id);

        public DelPlayFabError OnError;
        public DelPlayFabSuccess OnSuccess;

        public class UploadEvent
        {
            public string FilePath;
            public long ByteSize;

            public float SizeInMbs => (float) System.Math.Round((float)ByteSize / 1024f / 1024f, 2);
        }

        static List<UploadEvent> m_uploadEvents = new List<UploadEvent>();

        public static string GetUploadSummary()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            foreach (var ev in m_uploadEvents)
            {
                sb.Append(" - ");
                sb.Append(System.IO.Path.GetFileName(ev.FilePath));
                sb.Append(System.Environment.NewLine);
                sb.Append("   ");
                sb.Append(ev.SizeInMbs);
                sb.Append(" megabyte(s)");
                sb.Append(System.Environment.NewLine);
                sb.Append(System.Environment.NewLine);
            }

            sb.Append(System.Environment.NewLine);

            return sb.ToString();
        }

        public class GenericPlayFabContent
        {
            public string Id;
            public string Url;

            public enum ImageTyp
            {
                Thumbnail,
                Screenshot
            }

            public PlayFab.EconomyModels.Image ToPlayFabImage(ImageTyp imageType)
            {
                return new PlayFab.EconomyModels.Image()
                {
                    Id = this.Id,
                    Url = this.Url,

                    Type = imageType.ToString()
                };
            }

            public PlayFab.EconomyModels.Content ToPlayFabContent(string hash)
            {
                return new PlayFab.EconomyModels.Content()
                {
                    Id = this.Id,
                    Url = this.Url,

                    //MinClientVersion = hash,
                    //MaxClientVersion = hash
                };
            }
        }

        HashSet<string> m_cachedSubmissionIds = new HashSet<string>();

        string m_loggedInUserId;
        static string m_loggedInUserDisplayName;

        void PrepareUpload()
        {
            m_uploadEvents.Clear();
        }

        public void UploadAndPublish(Common.PublishInformation publishInfo, string previewPath, DelPublishSuccess publishSuccess)
        {
            PrepareUpload();

            EnterState("Uploading");

            if (!System.IO.File.Exists(previewPath))
            {
                LeaveState();

                throw new System.Exception("Missing thumbnail " + previewPath);
            }

            List<PlayFab.EconomyModels.UploadInfo> filesUploadInfo = new List<PlayFab.EconomyModels.UploadInfo>();

            filesUploadInfo.Add(
              new PlayFab.EconomyModels.UploadInfo()
              {
                  FileName = System.IO.Path.GetFileName(previewPath),
                  FileSize = (int)new System.IO.FileInfo(previewPath).Length
              });

            foreach (var mapPath in publishInfo.bundlePaths)
            {
                filesUploadInfo.Add(
                    new PlayFab.EconomyModels.UploadInfo()
                    {
                        FileName = System.IO.Path.GetFileName(mapPath),
                        FileSize = (int)new System.IO.FileInfo(mapPath).Length
                    });
            }

            PlayFabEconomyAPI.CreateUgcUploadUrls(new PlayFab.EconomyModels.CreateUploadUrlsRequest
                {
                    Files = filesUploadInfo
                },
                result => { Success(); Util.StartBackgroundTask(UploadPreviewAndMapAndPublish(publishInfo, previewPath, result, publishSuccess)); },
                PlayFabErrorHandler
                );
        }

        public void UploadAndUpdate(Common.PublishInformation publishInfo, string previewPath, DelPublishSuccess publishSuccess)
        {
            PrepareUpload();

            EnterState("Uploading");

            List<PlayFab.EconomyModels.UploadInfo> filesUploadInfo = new List<PlayFab.EconomyModels.UploadInfo>();

            filesUploadInfo.Add(
              new PlayFab.EconomyModels.UploadInfo()
              {
                  FileName = System.IO.Path.GetFileName(previewPath),
                  FileSize = (int)new System.IO.FileInfo(previewPath).Length
              });

            foreach (var mapPath in publishInfo.bundlePaths)
            {
                filesUploadInfo.Add(
                    new PlayFab.EconomyModels.UploadInfo()
                    {
                        FileName = System.IO.Path.GetFileName(mapPath),
                        FileSize = (int)new System.IO.FileInfo(mapPath).Length
                    });
            }

            PlayFabEconomyAPI.CreateUgcUploadUrls(new PlayFab.EconomyModels.CreateUploadUrlsRequest
                {
                    Files = filesUploadInfo
                },
                result => { Success(); Util.StartBackgroundTask(UploadPreviewAndMapAndUpdate(publishInfo, previewPath, result, publishSuccess)); },
                PlayFabErrorHandler
                );
        }

        List<PlayFab.EconomyModels.CatalogItemMetadata> m_cachedItemMetaInfo = new List<PlayFab.EconomyModels.CatalogItemMetadata>();

        PlayFabUtils.IdsQueryHandle m_submissionQueryHandle = null;

        public PlayFabUtils.IdsQueryHandle GetSubmissionQueryHandle()
        {
            if (m_submissionQueryHandle == null)
                m_submissionQueryHandle = new PlayFabUtils.IdsQueryHandle(new List<string>(m_cachedSubmissionIds));

            return m_submissionQueryHandle;
        }

        public List<PlayFab.EconomyModels.CatalogItemMetadata> GetCachedItems()
        {
            return m_cachedItemMetaInfo;
        }

        public void Delete(PlayFab.EconomyModels.CatalogItemMetadata item)
        {
            EnterState("Deleting");

            PlayFab.PlayFabEconomyAPI.DeleteUgcItem(new PlayFab.EconomyModels.DeleteItemRequest()
                {
                    ItemId = item.Id
                },
                result => { Success(); RemovePublishedId(item.Id); m_cachedItemMetaInfo.Remove(item); m_cachedSubmissionIds.Remove(item.Id); m_submissionQueryHandle.RemoveItem(item.Id); },
                PlayFabErrorHandler
                );
        }

        public void Update(PlayFab.EconomyModels.CatalogItemMetadata item, string title, string description, PlayFabUtils.ItemDisplayProperties itemDisplayProperties = null)
        {
            EnterState("Updating item");

            item.Title = new Dictionary<string, string>() { { "neutral", title } };
            item.Description = new Dictionary<string, string>() { { "neutral", description } };

            if (itemDisplayProperties != null)
                item.DisplayProperties = itemDisplayProperties;

            PlayFab.PlayFabEconomyAPI.UpdateDraftUgcItem(new PlayFab.EconomyModels.UpdateDraftItemRequest()
                {
                    Item = item,
                },
                result => { Success(); PublishDraft(item, null); },
                PlayFabErrorHandler
                );
        }

        IEnumerator UploadPreviewAndMapAndPublish(Common.PublishInformation publishInfo, string previewPath, PlayFab.EconomyModels.CreateUploadUrlsResult result, DelPublishSuccess publishSuccess)
        {
            List<GenericPlayFabContent> contentList = new List<GenericPlayFabContent>();

            IEnumerator uploadPreview = PlayFabUploadToUrl(previewPath, result.UploadUrls[0].Url, result, contentList);

            while (uploadPreview.MoveNext())
                yield return null;

            yield return null;

            for (int i = 0; i < publishInfo.bundlePaths.Count; ++i)
            {
                IEnumerator uploadMap = PlayFabUploadToUrl(publishInfo.bundlePaths[i], result.UploadUrls[1 + i].Url, result, contentList);

                while (uploadMap.MoveNext())
                    yield return null;
            }

            if (contentList.Count != 1 + publishInfo.bundlePaths.Count)
            {
                Error("Something went wrong.");

                yield break;
            }

            EnterState("Creating draft");

            var mapContents = new List<PlayFab.EconomyModels.Content>();

            for (int i = 0; i < publishInfo.bundlePaths.Count; ++i)
            {
                mapContents.Add(contentList[1 + i].ToPlayFabContent(""));
            }

            PlayFab.PlayFabEconomyAPI.CreateDraftUgcItem(
                new PlayFab.EconomyModels.CreateDraftItemRequest
                {
                    Item = new PlayFab.EconomyModels.CatalogItemMetadata
                    {
                        ContentType = "map",

                        IsHidden = true,

                        Title = new Dictionary<string, string>() { { "neutral", publishInfo.title } },
                        Description = new Dictionary<string, string>() { { "neutral", publishInfo.description } },

                        DisplayVersion = publishInfo.display_version,

                        Platforms = publishInfo.platforms,

                        Tags = new List<string>(publishInfo.tags),

                        DisplayProperties = CreateDisplayProperties(publishInfo),

                        Images = new List<PlayFab.EconomyModels.Image>() { contentList[0].ToPlayFabImage(GenericPlayFabContent.ImageTyp.Thumbnail) },
                        Contents = mapContents,
                    },
                },
                (draftResult) => { Success(); PublishDraft(draftResult.Item, publishSuccess); },
                PlayFabErrorHandler);
        }

        PlayFabUtils.ItemDisplayProperties CreateDisplayProperties(Common.PublishInformation publishInfo)
        {
            List<string> hashes = new List<string>(publishInfo.bundlePaths.Count);
            List<long> sizes = new List<long>(publishInfo.bundlePaths.Count);

            foreach (var path in publishInfo.bundlePaths)
            {
                hashes.Add(Common.GetMD5HashFromFile(path));
                sizes.Add(new System.IO.FileInfo(path).Length);
            }

            return new PlayFabUtils.ItemDisplayProperties()
            {
                hash = string.Join(",", hashes),
                pub_name = m_loggedInUserDisplayName,

                timestamp = System.DateTime.UtcNow.Ticks,

                env_type = publishInfo.env_type,
                map_size = publishInfo.map_size,
                time_of_day = publishInfo.time_of_day,

                pp_profile = publishInfo.pp_profile,

                // Lets just use the same tags
                //tags = publishInfo.tags,

                game_modes = publishInfo.game_modes,

                map_filesize = sizes,

                sdk_version = publishInfo.sdk_version,
                unity_version = publishInfo.unity_version,
                
                platforms = publishInfo.platforms
            };
        }

        IEnumerator UploadPreviewAndMapAndUpdate(Common.PublishInformation publishInfo, string previewPath, PlayFab.EconomyModels.CreateUploadUrlsResult result, DelPublishSuccess publishSuccess)
        {
            if (publishInfo.published_id.Length <= 0)
            {
                Error("Published id is empty.");

                yield break;
            }

            List<GenericPlayFabContent> contentList = new List<GenericPlayFabContent>();

            IEnumerator uploadPreview = PlayFabUploadToUrl(previewPath, result.UploadUrls[0].Url, result, contentList);

            while (uploadPreview.MoveNext())
                yield return null;

            yield return null;

            for (int i = 0; i < publishInfo.bundlePaths.Count; ++i)
            {
                IEnumerator uploadMap = PlayFabUploadToUrl(publishInfo.bundlePaths[i], result.UploadUrls[1 + i].Url, result, contentList);

                while (uploadMap.MoveNext())
                    yield return null;
            }

            if (contentList.Count != 1 + publishInfo.bundlePaths.Count)
            {
                Error("Something went wrong.");

                yield break;
            }

            EnterState("Updating draft");

            // This is a bit hard to read as it stacks three calls:
            // - GetPublishedUgcItem
            // - UpdateDraftUgcItem (wipes content)
            // - UpdateDraftUgcItem (sets new content)

            // Call 1
            PlayFab.PlayFabEconomyAPI.GetPublishedUgcItem(new PlayFab.EconomyModels.GetPublishedItemRequest()
            {
                ItemId = publishInfo.published_id
            },
            (getPublishedSuccess) =>
            {
                var oldImagesList          = new List<PlayFab.EconomyModels.Image>() { contentList[0].ToPlayFabImage(GenericPlayFabContent.ImageTyp.Thumbnail) };
              //  var oldContentsList = new List<PlayFab.EconomyModels.Content>();

                /*
                if (existingPlatform)
                {
                    // Update content
                    oldImagesList[contentPlatformIndex] = contentList[0].ToPlayFabImage(GenericPlayFabContent.ImageTyp.Thumbnail);
                    oldContentsList[contentPlatformIndex] = contentList[1].ToPlayFabContent("");
                }
                else
                {
                    // We never published anything for this platform yet. Lets append it as a new platform.
                    oldContentPlatforms.Add(PlayFabUtils.GetCurrentBuildPlatformName());

                    // PlayFab only allows to upload a single thumbnail per item.
                    oldImagesList = new List<PlayFab.EconomyModels.Image>() { contentList[0].ToPlayFabImage(GenericPlayFabContent.ImageTyp.Thumbnail) };

                    // Append new content URL
                    oldContentsList.Add(contentList[1].ToPlayFabContent(""));
                }*/



                // Wipe content
                getPublishedSuccess.Item.Contents = null;
                getPublishedSuccess.Item.Images = null;

                var mapContents = new List<PlayFab.EconomyModels.Content>();

                for (int i = 0; i < publishInfo.bundlePaths.Count; ++i)
                {
                    mapContents.Add(contentList[1 + i].ToPlayFabContent(""));
                }

                // Call 2
                PlayFab.PlayFabEconomyAPI.UpdateDraftUgcItem(
                new PlayFab.EconomyModels.UpdateDraftItemRequest
                {
                    Item = getPublishedSuccess.Item
                },
                updateWipeContentSuccess => 
                {
                    // Set updated content information
                    getPublishedSuccess.Item.Images = oldImagesList;
                    getPublishedSuccess.Item.Contents = mapContents;

                    // Set other information
                    getPublishedSuccess.Item.Title = new Dictionary<string, string>() { { "neutral", publishInfo.title } };
                    getPublishedSuccess.Item.Description = new Dictionary<string, string>() { { "neutral", publishInfo.description } };

                    getPublishedSuccess.Item.DisplayVersion = publishInfo.display_version;

                    getPublishedSuccess.Item.Platforms = publishInfo.platforms;

                    getPublishedSuccess.Item.DisplayProperties = CreateDisplayProperties(publishInfo);

                    getPublishedSuccess.Item.Tags = new List<string>(publishInfo.tags);

                    // Call 3
                    PlayFab.PlayFabEconomyAPI.UpdateDraftUgcItem(
                        new PlayFab.EconomyModels.UpdateDraftItemRequest
                        {
                            Item = getPublishedSuccess.Item
                        },
                        (draftResult) => { Success(); PublishDraft(draftResult.Item, publishSuccess); },
                        PlayFabErrorHandler);
                },
                PlayFabErrorHandler
                );
            },
            PlayFabErrorHandler
            );
        }

        IEnumerator PlayFabUploadToUrl(string filePath, string uploadUrl, PlayFab.EconomyModels.CreateUploadUrlsResult result, List<GenericPlayFabContent> contentList)
        {
            EnterState($"Uploading file {filePath}");

            m_activeState.Progress = 0f;

            // This functions uploads a file. In order to do this we need to split the file into multiple blocks that we upload to the CDN.
            // Every block needs its unique id, hash, etc.
            // We also need to keep track of all blocks we uploaded because we need to commit the blocklist at the end

            int ConvertMegabytesToBytes(int mb) => mb * 1000000;

            int BlockSize = ConvertMegabytesToBytes(100);

            long fileSize = -1;

            using (System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
            {
                fileSize = fileStream.Length;

                int blockCount = (int)((float)fileSize / (float)BlockSize) + 1;

                List<string> blockIDs = new List<string>();

                int blockNumber = 0;

                int bytesRead = 0;
                long bytesLeft = fileSize;

                // Loop until we uploaded all bytes
                while (bytesLeft > 0)
                {
                    blockNumber++;

                    int bytesToRead;

                    if (bytesLeft >= BlockSize)
                    {
                        // Allocates a full-sized block
                        bytesToRead = BlockSize;
                    }
                    else
                    {
                        // We got less bytes left than our block size
                        bytesToRead = (int)bytesLeft;
                    }

                    string blockId = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}",  blockNumber.ToString("0000000"))));

                    blockIDs.Add(blockId);

                    // Read number of bytes
                    byte[] bytes = new byte[bytesToRead];
                    fileStream.Read(bytes, 0, bytesToRead);

                    // Put block
                    string blockHash = Util.CalculateMD5HashBase64(bytes);

                    using (UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Put(uploadUrl + "&comp=block&blockid=" + blockId, bytes))
                    {
                        www.SetRequestHeader($"x-ms-blob-content-disposition", "attachment; filename=\"{fileName}\"");
                        www.SetRequestHeader("x-ms-blob-type", "BlockBlob");
                        www.SetRequestHeader("x-ms-blob-content-md5", blockHash);
                        www.SetRequestHeader("x-ms-client-request-id", blockId);

                        AsyncOperation op = www.SendWebRequest();

                        do
                        {
                            m_activeState.Progress = (float) (((double) bytesRead + (double)(www.uploadedBytes)) / (double) fileSize);

                            yield return null;

                            if (m_activeState.Progress == -1f)
                            {
                                Error("Aborted");

                                yield break;
                            }
                        } while (!op.isDone);

                        if (www.isNetworkError || www.isHttpError)
                        {
                            Error("Network error");

                            Debug.Log(www.error + "\n" + www.downloadHandler.text);

                            yield break;
                        }
                    }

                    // Keep track of our bytes
                    bytesRead += bytesToRead;
                    bytesLeft -= bytesToRead;
                }

                // Create a XML block list
                System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();

                strBuilder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
                strBuilder.Append("<BlockList>\n");

                for (int i = 0; i < blockIDs.Count; ++i)
                {
                    strBuilder.Append($"<Uncommitted>{blockIDs[i]}</Uncommitted>\n");
                }

                strBuilder.Append("</BlockList>\n");

                byte[] putBlockListBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(strBuilder.ToString());

                // Send the block list to make it compile all the blocks back into a single file
                using (UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Put(uploadUrl + "&comp=blocklist", putBlockListBytes))
                {
                    AsyncOperation op = www.SendWebRequest();

                    do
                    {
                        yield return null;

                        if (m_activeState.Progress == -1f)
                        {
                            Error("Aborted");

                            yield break;
                        }
                    } while (!op.isDone);

                    if (www.isNetworkError || www.isHttpError)
                    {
                        Error("Network error");

                        Debug.Log(www.error + "\n" + www.downloadHandler.text);

                        yield break;
                    }
                }
            }

            Success();

            Debug.Log($"Upload {filePath} complete!");

            m_uploadEvents.Add(new UploadEvent()
            {
                FilePath = filePath,
                ByteSize = fileSize
            });

            contentList.Add(new GenericPlayFabContent()
            {
                Id = System.IO.Path.GetFileName(filePath),
                Url = uploadUrl
            });
        }

        public void PublishDraft(PlayFab.EconomyModels.CatalogItemMetadata item, DelPublishSuccess publishSuccess)
        {
            EnterState("Publishing");

            PlayFabEconomyAPI.PublishUgcItem(
                new PlayFab.EconomyModels.PublishItemRequest
                {
                    ItemId = item.Id
                },
                (publishResult) => 
                {
                    Success();

                    publishSuccess?.Invoke(item.Id);

                    m_cachedSubmissionIds.Add(item.Id);
                    m_cachedItemMetaInfo.Add(item);

                    if (m_submissionQueryHandle != null)
                        m_submissionQueryHandle.AddItem(item);

                    Debug.Log($"Published! {item.Id}");

                    long fileSize = new System.IO.FileInfo(ContentBuilder.FullAssetBundlePath).Length;

                    UnityEditor.EditorUtility.DisplayDialog("Success!", $"Successfully uploaded files:\n\n{GetUploadSummary()}", "OK");

                    UnityEditor.EditorApplication.delayCall += delegate() { 
                        // Refresh
                        Onward.CustomContent.EditorTools.OnwardDashboard.FindComponents();
                    };
                },
                PlayFabErrorHandler);
        }

        public void AddPublishedId(string newId)
        {
            EnterState("Getting user data");

            PlayFab.PlayFabClientAPI.GetUserData(new PlayFab.ClientModels.GetUserDataRequest()
                {
                    PlayFabId = m_loggedInUserId
                },
                (userDataResult) => { Success(); SetUserDataUgcItems(userDataResult, newId, false); },
                PlayFabErrorHandler);
        }

        public void RemovePublishedId(string newId)
        {
            EnterState("Getting user data");

            PlayFab.PlayFabClientAPI.GetUserData(new PlayFab.ClientModels.GetUserDataRequest()
                {
                    PlayFabId = m_loggedInUserId
                },
                (userDataResult) => { Success(); SetUserDataUgcItems(userDataResult, newId, true); },
                PlayFabErrorHandler);
        }

        void SetUserDataUgcItems(PlayFab.ClientModels.GetUserDataResult userData, string id, bool remove)
        {
            EnterState("Updating user data");

            Dictionary<string, string> dictUsrData = new Dictionary<string, string>();

            if (remove)
            {
                List<string> ids = new List<string>(userData.Data[UgcItemsKey].Value.Split(','));

                ids.Remove(id);

                if (ids.Count > 0)
                {
                    string tmp = ids[0];

                    for (int i = 1; i < ids.Count; ++i)
                    {
                        tmp += "," + ids[i];
                    }

                    dictUsrData.Add(UgcItemsKey, tmp);
                }
                else
                {
                    PlayFab.PlayFabClientAPI.UpdateUserData(new PlayFab.ClientModels.UpdateUserDataRequest()
                        {
                            KeysToRemove = new List<string>() { UgcItemsKey }
                        },
                        (res) => { Success(); },
                        PlayFabErrorHandler); ;

                    return;
                }
            }
            else
            {
                if (!userData.Data.ContainsKey(UgcItemsKey))
                {
                    dictUsrData.Add(UgcItemsKey, id);
                }
                else
                {
                    dictUsrData.Add(UgcItemsKey, userData.Data[UgcItemsKey].Value + "," + id);
                }
            }

            PlayFab.PlayFabClientAPI.UpdateUserData(new PlayFab.ClientModels.UpdateUserDataRequest()
                {
                    Data = dictUsrData
                },
                (res) => { Success(); },
                PlayFabErrorHandler); ;
        }

        public void Login(string mail, string password)
        {
            if (IsLoggedIn())
            {
                return;
            }

            EnterState("Logging in");

            PlayFab.PlayFabClientAPI.LoginWithEmailAddress(
                   new PlayFab.ClientModels.LoginWithEmailAddressRequest()
                   {
                       TitleId = TitleId,

                       Email = mail,
                       Password = password,

                       InfoRequestParameters = new PlayFab.ClientModels.GetPlayerCombinedInfoRequestParams()
                       {
                           GetUserAccountInfo = true
                       }
                   }, 
                   result =>
                   {
                       bool IsNameInvalid(string x) => string.IsNullOrEmpty(m_loggedInUserDisplayName) || m_loggedInUserDisplayName.ToLower() == "null";

                       Success();
                                   
                       m_loggedInUserId = result.PlayFabId;

                       m_loggedInUserDisplayName = result.InfoResultPayload.AccountInfo.TitleInfo.DisplayName;

                       // Fall back to the username if the display name is not available
                       if (IsNameInvalid(m_loggedInUserDisplayName))
                       {
                           m_loggedInUserDisplayName = result.InfoResultPayload.AccountInfo.Username;
                       }

                       // Nothing we can do anymore...
                       if (IsNameInvalid(m_loggedInUserDisplayName))
                       {
                           m_loggedInUserDisplayName = "????????";
                       }

                       UpdateCachedSubmissions();
                   },
                   PlayFabErrorHandler
                   );
        }

        void UpdateCachedSubmissions()
        {
            EnterState("Getting user data");

            PlayFab.PlayFabClientAPI.GetUserData(new PlayFab.ClientModels.GetUserDataRequest()
                {
                    PlayFabId = m_loggedInUserId
                },
                (userDataResult) => 
                {
                    Success();

                    m_cachedSubmissionIds.Clear();

                    if (userDataResult.Data.ContainsKey(UgcItemsKey))
                    {
                        m_cachedSubmissionIds.UnionWith(userDataResult.Data[UgcItemsKey].Value.Split(','));
                    }
                },
                PlayFabErrorHandler);
        }

        public void CreateAccount(string username, string mail, string password)
        {
            EnterState("Creating account");

            PlayFab.PlayFabClientAPI.RegisterPlayFabUser(
                    new PlayFab.ClientModels.RegisterPlayFabUserRequest()
                    {
                        Username = username,
                        DisplayName = username,

                        Email = mail,
                        Password = password,

                        RequireBothUsernameAndEmail = true
                    },
                    result => 
                    {
                        Success();

                        m_loggedInUserId = result.PlayFabId;
                        m_loggedInUserDisplayName = username;

                        UpdateCachedSubmissions();
                    },
                    PlayFabErrorHandler 
                    );
        }

        public void ResetPassword(string mail)
        {
            EnterState("Requesting mail");

            PlayFab.PlayFabClientAPI.SendAccountRecoveryEmail(new PlayFab.ClientModels.SendAccountRecoveryEmailRequest()
            {
                Email = mail,
                TitleId = TitleId,
            },
            result =>
            {
                Success();
            },
            PlayFabErrorHandler
            );
        }

        public void Logout()
        {
            PlayFabClientAPI.ForgetAllCredentials();

            m_loggedInUserId = "";
            m_loggedInUserDisplayName = "";

            m_cachedItemMetaInfo.Clear();
            m_cachedSubmissionIds.Clear();
        }

        public void CancelRequest()
        {
            // We just set progress to -1 to indicate user cancellation
            // Only operations that use this can be cancelled and need to check for -1

            m_activeState.Progress = -1f;
        }

        public bool IsLoggedIn()
        {
            return PlayFabClientAPI.IsClientLoggedIn();
        }

        public PlayFabUtils.HelperState GetState()
        {
            return m_activeState;
        }

        Stack<PlayFabUtils.HelperState> m_stateStack = new Stack<PlayFabUtils.HelperState>();
        PlayFabUtils.HelperState m_activeState = new PlayFabUtils.HelperState() { Message = "", Progress = -1f, State = PlayFabUtils.HelperState.EState.Ready };

        void EnterState(string msg)
        {
            PlayFabUtils.HelperState newState = new PlayFabUtils.HelperState()
            {
                Message = msg,
                State = PlayFabUtils.HelperState.EState.Pending,
                Progress = -1f
            };

            m_stateStack.Push(newState);

            m_activeState = newState;
        }

        void LeaveState()
        {
            PlayFabUtils.HelperState state = m_stateStack.Pop();

            if (m_stateStack.Count > 0)
            {
                m_activeState = state;

                return;
            }

            m_activeState = new PlayFabUtils.HelperState() { Message = "", Progress = -1f, State = PlayFabUtils.HelperState.EState.Ready };
        }

        // Some callbacks
        void Success()
        {
            LeaveState();

            OnSuccess?.Invoke();
        }

        void PlayFabErrorHandler(PlayFabError error)
        {
            Error(error.GenerateErrorReport());
        }

        void Error(string msg)
        {
            LeaveState();

            OnError?.Invoke(msg);
        }
    }
}