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

namespace Onward.CustomContent
{
    public static class PlayFabUtils
    {
        public class CatalogQueryHandle
        {
            public enum QueryState
            {
                Ready,
                Error,
                Pending
            }

            public int TotalPageCount { get; private set; } = 0;
            public int TotalCount { get; private set; } = 0;
            public int ActivePage { get; private set; } = 1;

            public QueryState State { get; private set; } = QueryState.Ready;

            const int MaxPageSize = 10;

            public List<PlayFab.EconomyModels.CatalogItemMetadata> ItemsOnPage { get; } = new List<PlayFab.EconomyModels.CatalogItemMetadata>();

            public delegate void DelCompletion(List<PlayFab.EconomyModels.CatalogItemMetadata> items);
            public delegate void DelNewItems(List<PlayFab.EconomyModels.CatalogItemMetadata> items);

            public DelCompletion OnRepopulatePage;
            public DelNewItems OnNewItemsReceived;

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

            public CatalogQueryHandle()
            {
                BeginQuery();
            }

            public bool HasPrevPage()
            {
                return ActivePage > 1;
            }

            public bool HasNextPage()
            {
                return ActivePage < TotalPageCount;
            }

            public void NextPage()
            {
                if (!HasNextPage())
                    return;

                // Wait for all requests to finish
                if (State == QueryState.Pending)
                    return;

                ++ActivePage;

                // Query if we ran out of entries
                if (m_allItems.Count != TotalCount && m_allItems.Count < ActivePage * MaxPageSize)
                {
                    BeginQuery();

                    return;
                }

                Repopulate();
            }

            public void PrevPage()
            {
                if (!HasPrevPage())
                    return;

                // Wait for all requests to finish
                if (State == QueryState.Pending)
                    return;

                --ActivePage;

                Repopulate();
            }

            void Repopulate()
            {
                if (m_allItems.Count <= 0)
                    return;

                ItemsOnPage.Clear();

                int startIndex = MaxPageSize * (ActivePage - 1);

                int totalCount = startIndex + MaxPageSize;

                if (totalCount > m_allItems.Count)
                {
                    ItemsOnPage.AddRange(m_allItems.GetRange(MaxPageSize * (ActivePage - 1), m_allItems.Count - startIndex));
                }
                else
                {
                    ItemsOnPage.AddRange(m_allItems.GetRange(MaxPageSize * (ActivePage - 1), MaxPageSize));
                }

                OnRepopulatePage?.Invoke(ItemsOnPage);
            }

            // Callbacks
            void BeginQuery()
            {
                ItemsOnPage.Clear();

                State = QueryState.Pending;

                PlayFab.PlayFabEconomyAPI.Search(
                      new PlayFab.EconomyModels.CatalogSearchRequest()
                      {
                          Select = "contents,images",
                          Skip = m_allItems.Count,
                          Top = MaxPageSize
                      },
                      (res) => { CompleteQuery(res); },
                      (error) => { CompleteWithError(); }
                      );
            }

            void CompleteQuery(PlayFab.EconomyModels.CatalogSearchResult result)
            {
                State = QueryState.Ready;

                TotalCount = result.Count.Value;
                TotalPageCount = Mathf.CeilToInt((float)result.Count.Value / (float)MaxPageSize);

                ActivePage = Mathf.Clamp(ActivePage, 0, TotalPageCount);

                m_allItems.AddRange(result.Items);

                Repopulate();

                OnNewItemsReceived?.Invoke(result.Items);
            }

            void CompleteWithError()
            {
                State = QueryState.Error;
            }
        }

        public class IdsQueryHandle
        {
            const int MaxPageSize = 10;

            public int TotalPageCount { get; private set; } = 0;
            public int TotalCount { get; private set; } = 0;
            public int ActivePage { get; private set; } = 1;

            public class ItemHandle
            {
                public PlayFab.EconomyModels.CatalogItemMetadata Item = null;

                public bool Valid = false;
            }

            List<ItemHandle> m_allItems = new List<ItemHandle>();
            public List<ItemHandle> ItemsOnPage { get; } = new List<ItemHandle>();

            public delegate void DelCompletion(List<ItemHandle> items);
            public delegate void DelNewItems(List<ItemHandle> items);

            public DelCompletion OnRepopulatePage;
            public DelNewItems OnNewItemsReceived;

            int m_validItemCount = 0;

            public IdsQueryHandle(List<string> ids)
            {
                for (int i = 0; i < ids.Count; ++i)
                {
                    // Populate with dummy data
                    ItemHandle newItemHandle = new ItemHandle();

                    newItemHandle.Item = new PlayFab.EconomyModels.CatalogItemMetadata()
                    {
                        Id = ids[i],

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

                        IsHidden = false,

                        Contents = new List<PlayFab.EconomyModels.Content>()
                    {
                        new PlayFab.EconomyModels.Content() { Id = "", Url = "" }
                    },

                        Images = new List<PlayFab.EconomyModels.Image>()
                    {
                        new PlayFab.EconomyModels.Image() { Id = "", Url = "" }
                    }
                    };

                    m_allItems.Add(newItemHandle);
                }

                TotalCount = m_allItems.Count;
                TotalPageCount = Mathf.CeilToInt((float)m_allItems.Count / (float)MaxPageSize);

                BeginQuery();
            }

            public bool HasPrevPage()
            {
                return ActivePage > 1;
            }

            public bool HasNextPage()
            {
                return ActivePage < TotalPageCount;
            }

            public void NextPage()
            {
                if (!HasNextPage())
                    return;

                ++ActivePage;

                // Query if we ran out of entries
                if (m_validItemCount != TotalCount
                    && m_validItemCount < ActivePage * MaxPageSize)
                {
                    BeginQuery();

                    return;
                }

                Repopulate();
            }

            public void PrevPage()
            {
                if (!HasPrevPage())
                    return;

                --ActivePage;

                Repopulate();
            }

            public void RemoveItem(string id)
            {
                for (int i = 0; i < m_allItems.Count; ++i)
                {
                    if (m_allItems[i].Item.Id == id)
                    {
                        m_allItems.RemoveAt(i);

                        break;
                    }
                }

                Repopulate();
            }

            public void AddItem(PlayFab.EconomyModels.CatalogItemMetadata item)
            {
                for (int i = 0; i < m_allItems.Count; ++i)
                {
                    if (m_allItems[i].Item.Id == item.Id)
                    {
                        return;
                    }
                }

                m_allItems.Add(new ItemHandle()
                {
                    Item = item,
                    Valid = true
                });

                Repopulate();
            }

            void Repopulate()
            {
                TotalCount = m_allItems.Count;
                TotalPageCount = Mathf.CeilToInt((float)m_allItems.Count / (float)MaxPageSize);

                ActivePage = Mathf.Clamp(ActivePage, 0, TotalPageCount);

                if (m_allItems.Count <= 0)
                    return;

                ItemsOnPage.Clear();

                int startIndex = MaxPageSize * (ActivePage - 1);

                int totalCount = startIndex + MaxPageSize;

                if (totalCount > m_allItems.Count)
                {
                    ItemsOnPage.AddRange(m_allItems.GetRange(MaxPageSize * (ActivePage - 1), m_allItems.Count - startIndex));
                }
                else
                {
                    ItemsOnPage.AddRange(m_allItems.GetRange(MaxPageSize * (ActivePage - 1), MaxPageSize));
                }

                OnRepopulatePage?.Invoke(ItemsOnPage);
            }

            // Callbacks
            void BeginQuery()
            {
                if (m_validItemCount >= m_allItems.Count)
                    return;

                ItemsOnPage.Clear();

                int queryCount = MaxPageSize;

                if (m_validItemCount + MaxPageSize > m_allItems.Count)
                {
                    queryCount = m_allItems.Count - m_validItemCount;
                }

                for (int i = m_validItemCount; i < m_validItemCount + queryCount; ++i)
                {
                    ItemHandle itemHandle = m_allItems[i];

                    PlayFab.PlayFabEconomyAPI.GetPublishedUgcItem(new PlayFab.EconomyModels.GetPublishedItemRequest()
                        {
                            ItemId = itemHandle.Item.Id
                        },
                        result =>
                        {
                            itemHandle.Item = result.Item;

                            itemHandle.Valid = true;

                            OnNewItemsReceived?.Invoke(new List<ItemHandle>() { itemHandle });
                        },
                        error =>
                        {
                            itemHandle.Item.Title = new Dictionary<string, string>() { { "neutral", "Query error" } };
                            itemHandle.Item.Description = new Dictionary<string, string>() { { "neutral", error.GenerateErrorReport() } };
                        }
                        );
                }

                m_validItemCount += queryCount;

                Repopulate();
            }
        }

        public class TextureCache
        {
            public class TextureState
            {
                public Texture texture;

                public float progress;

                public bool isDone;
            }

            Dictionary<string, TextureState> m_cache = new Dictionary<string, TextureState>();

            MonoBehaviour m_hostBehaviour;

            public TextureCache(MonoBehaviour hostBehaviour)
            {
                m_hostBehaviour = hostBehaviour;
            }

            public TextureState ResolveTexture(string url)
            {
                if (m_cache.TryGetValue(url, out TextureState state))
                {
                    return state;
                }

                TextureState newState = new TextureState();

                m_cache.Add(url, newState);

                m_hostBehaviour.StartCoroutine(DownloadTexture(url, newState));

                return newState;
            }

            IEnumerator DownloadTexture(string url, TextureState state)
            {
                state.isDone = false;

                UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequestTexture.GetTexture(url);

                request.SendWebRequest();

                while (!request.isDone)
                {
                    state.progress = request.downloadProgress;

                    yield return null;
                }

                if (request.isNetworkError || request.isHttpError)
                {
                    // We could retry but if it fails there probably is some server issue and we would just retry again and again
                    state.isDone = true;
                }
                else
                {
                    yield return null;

                    state.texture = ((UnityEngine.Networking.DownloadHandlerTexture)request.downloadHandler).texture;
                    state.isDone = true;
                }
            }
        }

        public struct HelperState
        {
            public enum EState
            {
                Ready,
                Pending
            }

            public EState State;
            public string Message;
            public float Progress;
        }

        [System.Serializable]
        public class ItemDisplayProperties
        {
            public string hash;
            public string pub_name;

            public long timestamp;

            public string env_type;
            public string map_size;
            public string time_of_day;

            public string pp_profile;

            //public string[] tags;

            public string[] game_modes;

            public List<long> map_filesize = new List<long>();

            public string unity_version;
            public string sdk_version;

            public List<string> platforms = new List<string>();
        }

        public enum ItemState
        {
            Unsubscribed,
            Subscribed,
            Outdated,
            Corrupt,
        }

        public static List<string> GetBuildPlatform()
        {
            return new List<string>()
            {
#if UNITY_STANDALONE_WIN
                "Standalone_Windows"
        #elif UNITY_ANDROID
                "Standalone_Android"
        #endif
            };
        }

        public static string GetTargetPlatformName()
        {
            const string Windows = "Standalone_Windows";
            const string Android = "Standalone_Android";

#if UNITY_EDITOR
            switch (UnityEditor.EditorUserBuildSettings.activeBuildTarget)
            {
                case UnityEditor.BuildTarget.StandaloneWindows64:
                    return Windows;

                case UnityEditor.BuildTarget.Android:
                    return Android;
            }
#endif

#if UNITY_STANDALONE_WIN
            return Windows;
#elif UNITY_ANDROID
            return Android;
#endif

            throw new System.Exception("Unsupported platform");
        }

        public static ItemDisplayProperties DeserializeDisplayProperties(this PlayFab.EconomyModels.CatalogItemMetadata metadata)
        {
            if (metadata?.DisplayProperties == null)
                return null;

            return PlayFab.Json.PlayFabSimpleJson.DeserializeObject<ItemDisplayProperties>(metadata.DisplayProperties.ToString());
        }
    }
}