﻿#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace Onward.CustomContent.EditorTools
{
    public class OnwardDashboard : EditorWindow
    {
        static PlayFabUploadHelper m_playFabHelper = null;

        string m_username = "";
        string m_mail = "";

        string m_password;
        string m_passwordConfirm;

        enum StartScreenState
        {
            Login,
            Create,
            ForgotPassword
        }

        StartScreenState m_startScreenState = StartScreenState.Login;

        enum DashboardScreenState
        {
            Upload,
            Browse
        }

        DashboardScreenState m_dashboardScreenState = DashboardScreenState.Upload;

        static Texture2D m_logo;
        static Onward.CustomContent.Assets.LevelDescriptor m_levelDesc;

        public class ImageCacheEntry
        {
            public Texture texture = null;
            public float progress = 0f;
        }

        static Dictionary<string, ImageCacheEntry> m_imageCache = new Dictionary<string, ImageCacheEntry>();

        [MenuItem("ONWARD/SDK Version")]
        public static void ShowSDKVersion()
        {
            UnityEditor.EditorUtility.DisplayDialog("SDK Version", $"SDK Version: {Global.SdkVersion}", "OK");
        }

        [MenuItem("ONWARD/Onward Dashboard")]
        public static void ShowWorkshopWindow()
        {
            FindComponents();

            OnwardDashboard onwardDashboard = GetWindow<OnwardDashboard>(false, "Onward Dashboard", true);

            onwardDashboard.AddCallbacks(true);
        }

        public static void FindComponents()
        {
            if (m_playFabHelper == null)
            {
                m_playFabHelper = new PlayFabUploadHelper();
            }

            if (m_logo == null)
            {
                m_logo = Resources.Load<Texture2D>("onward_logo");
            }

            m_levelDesc = GameObject.FindObjectOfType<Onward.CustomContent.Assets.LevelDescriptor>();
        }

        void OnSelectionChange()
        {
            FindComponents();

            Repaint();
        }

        private void OnProjectChange()
        {
            FindComponents();

            Repaint();
        }

        private void OnDestroy()
        {
            AddCallbacks(false);
        }

        public void AddCallbacks(bool add)
        {
            if (m_playFabHelper == null)
                return;

            if (add)
            {
                m_playFabHelper.OnError += OnPlayFabError;
                m_playFabHelper.OnSuccess += OnPlayFabSuccess;
            }
            else
            {
                m_playFabHelper.OnError -= OnPlayFabError;
                m_playFabHelper.OnSuccess -= OnPlayFabSuccess;
            }
        }

        private void OnGUI()
        {
            GUI.DrawTexture(new Rect(35, 0, 460, 215), m_logo);

            GUILayout.Space(215);

            if (m_playFabHelper == null)
                return;

            PlayFabUtils.HelperState state = m_playFabHelper.GetState();

            if (state.State == PlayFabUtils.HelperState.EState.Pending)
            {
                GUILayout.Label("Please wait...");

                if (state.Progress >= 0f)
                {
                    if (EditorUtility.DisplayCancelableProgressBar(state.Message, state.Message, state.Progress))
                    {
                        m_playFabHelper.CancelRequest();
                    }
                }
                else
                {
                    EditorUtility.DisplayProgressBar(state.Message, state.Message, 0.5f);
                }

                Repaint();

                return;
            }

            if (m_playFabHelper.IsLoggedIn())
            {
                DashboardScreen();
            }
            else
            {
                StartScreen();
            }

            GUILayout.Space(25);

           
        }

        Vector2 m_scrollPositionUpload;
        Vector2 m_scrollPositionBrowse;

        void DashboardScreen()
        {
            if (UnityEditor.BuildPipeline.isBuildingPlayer)
            {
                GUILayout.Label("Build in progress. Please wait.", EditorStyles.boldLabel);

                return;
            }

            if (m_levelDesc == null)
            {
                GUILayout.Label("Your scene is missing the LevelDescriptor prefab.\nAdd it to your scene to fix this issue.\n\nNOTICE: You can ignore this error when a build is in progress.", EditorStyles.boldLabel);

                return;
            }

            if (m_levelDesc.SharedSettings == null)
            {
                GUILayout.Label("You need to create and assign a SharedSettings object to your LevelDescriptor.\n\nNOTICE: You can ignore this error when a build is in progress.", EditorStyles.boldLabel);

                return;
            }

            m_dashboardScreenState = (DashboardScreenState) GUILayout.Toolbar((int) m_dashboardScreenState, new string[] { "Publish/Update", "My items" });

            GUILayout.Space(20);

            switch (m_dashboardScreenState)
            {
                case DashboardScreenState.Upload:
                    Upload();
                    break;

                case DashboardScreenState.Browse:
                    Browse();
                    break;
            }

            if (GUILayout.Button("Logout"))
            {
                m_playFabHelper.Logout();
            }
        }

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

        bool AreTermsAccepted
        {
            get
            {
                return EditorPrefs.GetBool("_onward_accepted_tos", false);
            }

            set
            {
                EditorPrefs.SetBool("_onward_accepted_tos", value);
            }
        }

        void Upload()
        {
            m_errors.Clear();

            m_scrollPositionUpload = GUILayout.BeginScrollView(m_scrollPositionUpload);

            GUILayout.Label("Title:", EditorStyles.boldLabel);

            m_levelDesc.SharedSettings.Title = EditorGUILayout.TextArea(m_levelDesc.SharedSettings.Title);

            GUILayout.Space(25);

            GUILayout.Label("Description:", EditorStyles.boldLabel);
            m_levelDesc.SharedSettings.Description = EditorGUILayout.TextArea(m_levelDesc.SharedSettings.Description, GUILayout.MaxHeight(75));

            GUILayout.Space(25);

            m_levelDesc.SharedSettings.MapEnvType = (Onward.CustomContent.Assets.LevelDescriptor.EMapEnvironment) EditorGUILayout.EnumPopup("Map enviroment:", m_levelDesc.SharedSettings.MapEnvType);
            m_levelDesc.SharedSettings.MapSize = (Onward.CustomContent.Assets.LevelDescriptor.EMapSize)EditorGUILayout.EnumPopup("Map size:", m_levelDesc.SharedSettings.MapSize);
            m_levelDesc.SharedSettings.TimeOfDay = (Onward.CustomContent.Assets.LevelDescriptor.ETimeOfDay)EditorGUILayout.EnumPopup("Time of day:", m_levelDesc.SharedSettings.TimeOfDay);
            m_levelDesc.SharedSettings.PPProfileId = (Onward.CustomContent.Assets.LevelDescriptor.EProfileId)EditorGUILayout.EnumPopup("Post processing profile:", m_levelDesc.SharedSettings.PPProfileId);

            GUILayout.Space(25);

            const int ThumbWidth = 512;
            const int ThumbHeight = 256;

            GUILayout.Label("Preview:", EditorStyles.boldLabel);
            m_levelDesc.SharedSettings.Thumbnail = EditorGUILayout.ObjectField($"Thumbnail [{ThumbWidth}x{ThumbHeight} px]", m_levelDesc.SharedSettings.Thumbnail, typeof(Texture2D), false) as Texture2D;

            GUILayout.Label("Display version:", EditorStyles.boldLabel);
            m_levelDesc.SharedSettings.DisplayVersion = EditorGUILayout.TextArea(m_levelDesc.SharedSettings.DisplayVersion, GUILayout.MaxHeight(75));

            GUILayout.Space(25);

            AreTermsAccepted = GUILayout.Toggle(AreTermsAccepted, " I agree to the following terms and conditions:");

            ShowClickableLink("http://www.downpourinteractive.com/custom-content-agreement");
            ShowClickableLink("http://www.downpourinteractive.com/eula");
            ShowClickableLink("http://www.downpourinteractive.com/privacy-policy");
            ShowClickableLink("https://www.playfab.com/terms");

            GUILayout.Space(5);

            if (!AreTermsAccepted)
                m_errors.Add("You need to review and agree the terms of services.");

            if (m_levelDesc != null)
            {
                EditorUtility.SetDirty(m_levelDesc);

                if (m_levelDesc.SharedSettings != null)
                {
                    EditorUtility.SetDirty(m_levelDesc.SharedSettings);
                }
            }

            if (m_levelDesc.SharedSettings.Title.Length <= 0)
                m_errors.Add("Missing title");

            if (m_levelDesc.SharedSettings.Description.Length <= 0)
                m_errors.Add("Missing description");

            if (m_levelDesc.SharedSettings.DisplayVersion.Length <= 0)
                m_errors.Add("Missing display version");

            if (m_levelDesc.SharedSettings.Thumbnail == null)
            {
                m_errors.Add("Missing thumbnail");
            }
            else
            {
                if (m_levelDesc.SharedSettings.Thumbnail.width != ThumbWidth || m_levelDesc.SharedSettings.Thumbnail.height != ThumbHeight)
                {
                    m_errors.Add($"Thumbnail resolution needs to be {ThumbWidth}x{ThumbHeight} px");
                }
            }

            // If users choose to use the ExampleScene as a starting point they might end up overwriting it.
            // Thats because our template project and updates to it will always contain this scene as well.
            // Enforcing a different name reduces the chance for this to happen.
            if (UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name.ToLower() == "examplescene")
            {
                m_errors.Add("Rename your scene to anything but 'ExampleScene'. This name is prohibited to avoid potential data loss due to accidental overwrites (e.g. during updates).");
            }

            if (m_errors.Count > 0)
            {
                for (int i = 0; i < m_errors.Count; ++i)
                    EditorGUILayout.HelpBox(m_errors[i], MessageType.Error);
            }
            else
            {
                EditorGUILayout.HelpBox("If you are running into issues like long build durations / high memory consumption please consider changing the Shader Stripping options.\n\nYou can find the Shader Stripping settings here:\n     Edit -> Project Settings -> Graphics\n\n", MessageType.Warning);

                GUILayout.Space(5);

                bool isUpdate = m_levelDesc.SharedSettings.PublishedItemId.Length > 0;

                if (isUpdate)
                {
                    GUI.enabled = false;

                    EditorGUILayout.TextField("Updating submission with id:", m_levelDesc.SharedSettings.PublishedItemId);

                    GUI.enabled = true;

                    if (GUILayout.Button("Update"))
                    {
                        UpdateSubmission();
                    }
                }
                else
                {
                    if (GUILayout.Button("Publish"))
                    {
                        if (UnityEditor.EditorUtility.DisplayDialog("Evaluation process", "You are about to submit your creation. Thank you for that!\n\nPlease allow up to two weeks for evaluation.\n\nYou will be informed about the result via mail or Discord.", "OK", "Cancel"))
                        {
                            PublishSubmission();
                        }
                    }
                }
            }

            GUILayout.EndScrollView();
        }

        PlayFabUtils.IdsQueryHandle m_subQueryHandle;

        void Browse()
        {
            if (m_subQueryHandle == null)
            {
                m_subQueryHandle = m_playFabHelper.GetSubmissionQueryHandle();

                // Just to make it more responsive
                m_subQueryHandle.OnRepopulatePage = (items) => { Repaint(); };
            }

            GUILayout.Label($"Total: {m_subQueryHandle.TotalCount}, Page: {m_subQueryHandle.ActivePage}/{m_subQueryHandle.TotalPageCount}", EditorStyles.boldLabel);

            m_scrollPositionUpload = GUILayout.BeginScrollView(m_scrollPositionUpload);

            for (int i = 0; i < m_subQueryHandle.ItemsOnPage.Count; ++i)
            {
                PlayFabUtils.IdsQueryHandle.ItemHandle itemHandle = m_subQueryHandle.ItemsOnPage[i];

                GUILayout.BeginHorizontal();

                GUI.enabled = itemHandle.Valid;

                ImageCacheEntry entry;
                if (m_imageCache.TryGetValue(itemHandle.Item.Images[0].Url, out entry))
                {
                    GUILayout.Box(entry.texture == null ? m_logo : entry.texture, GUILayout.Width(100), GUILayout.Height(100));
                }
                else
                {
                    GUILayout.Box(m_logo, GUILayout.Width(100), GUILayout.Height(100));

                    // We only do this during Repaint as it could cause a different number of controls in Repaint and Layout otherwise
                    if (Event.current.type == EventType.Repaint)
                    {
                        m_imageCache.Add(itemHandle.Item.Images[0].Url, new ImageCacheEntry());

                        Util.StartBackgroundTask(DownloadImageAndCache(itemHandle.Item.Images[0].Url));
                    }
                }

                GUILayout.BeginVertical();

                GUILayout.Label(itemHandle.Item.Title["neutral"], EditorStyles.boldLabel);
                GUILayout.Label(itemHandle.Item.Description["neutral"]);

                // This can be invalid when not released yet
                if (itemHandle.Item.Rating != null && itemHandle.Item.Rating.Average.HasValue)
                {
                    GUILayout.Label("Rating: " + (itemHandle.Item.Rating.Average.HasValue ? $"{itemHandle.Item.Rating.Average}/5" : "-"));
                }

                GUILayout.Label("Version: " + itemHandle.Item.DisplayVersion);

                GUILayout.Label(itemHandle.Item.IsHidden.Value ? "IN REVIEW" : "LIVE", EditorStyles.boldLabel);

                GUILayout.TextField(itemHandle.Item.Id);

                GUILayout.EndVertical();

                GUILayout.EndHorizontal();

                if (GUILayout.Button($"Edit '{itemHandle.Item.Title["neutral"]}'"))
                {
                    GetWindow<OnwardEditItem>(true, "Edit item", true).Init(m_playFabHelper, itemHandle.Item);
                }

                GUI.enabled = true;

                GUILayout.Space(25);
            }

            GUILayout.EndScrollView();

            GUILayout.BeginHorizontal();

            GUI.enabled = m_subQueryHandle.HasPrevPage();
            if (GUILayout.Button("<< Prev"))
            {
                m_subQueryHandle.PrevPage();
            }
            GUI.enabled = true;

            GUI.enabled = m_subQueryHandle.HasNextPage();
            if (GUILayout.Button("Next >>"))
            {
                m_subQueryHandle.NextPage();
            }
            GUI.enabled = true;

            GUILayout.EndHorizontal();
        }

        void StartScreen()
        {
            m_startScreenState = (StartScreenState) GUILayout.Toolbar((int)m_startScreenState, new string[] { "Existing account", "Create new account", "Forgot password" });

            GUILayout.Space(20);

            switch (m_startScreenState)
            {
                case StartScreenState.Login:
                    GUILayout.Label("Login", EditorStyles.boldLabel);

                    m_mail = EditorGUILayout.TextField("Mail:", m_mail);
                    m_password = EditorGUILayout.PasswordField("Password:", m_password);

                    if (GUILayout.Button("Login"))
                    {
                        m_playFabHelper.Login(m_mail, m_password);

                        m_password = "";
                    }
                    break;

                case StartScreenState.Create:
                    {
                        GUILayout.Label("Create new account", EditorStyles.boldLabel);

                        m_username = EditorGUILayout.TextField("Username:", m_username).Trim();

                        m_mail = EditorGUILayout.TextField("Mail:", m_mail);

                        m_password = EditorGUILayout.PasswordField("Password:", m_password);
                        m_passwordConfirm = EditorGUILayout.PasswordField("Password (confirm):", m_passwordConfirm);

                        bool error = false;

                        if (m_username.Length < 3)
                        {
                            EditorGUILayout.HelpBox("Missing username.", MessageType.Error);

                            error = true;
                        }

                        if (m_mail.Length < 3 || m_mail.IndexOf('@') == -1 || m_mail.IndexOf('.') == -1)
                        {
                            EditorGUILayout.HelpBox("Missing valid mail.", MessageType.Error);

                            error = true;
                        }

                        if (m_password != m_passwordConfirm)
                        {
                            EditorGUILayout.HelpBox("Passwords do not match.", MessageType.Error);

                            error = true;
                        }

                        if (!error)
                        {
                            EditorGUILayout.HelpBox("Please make sure to enter a mail address that you check regularly.\n\nIt will also be used to inform you about the evaluation process of your submission.", MessageType.Warning);
                        }

                        GUI.enabled = !error;

                        if (GUILayout.Button("Create"))
                        {
                            if (m_password != m_passwordConfirm)
                            {
                                m_password = m_passwordConfirm = "";

                                EditorUtility.DisplayDialog("Passwords do not match.", "Passwords do not match.", "OK");

                                return;
                            }

                            m_playFabHelper.CreateAccount(m_username, m_mail, m_password);

                            m_password = "";

                            m_startScreenState = StartScreenState.Login;
                        }

                        GUI.enabled = true;
                }
                    break;

                case StartScreenState.ForgotPassword:
                    {
                        GUILayout.Label("Forgot password", EditorStyles.boldLabel);

                        m_mail = EditorGUILayout.TextField("Mail:", m_mail);

                        bool error = false;

                        if (m_mail.Length < 3 || m_mail.IndexOf('@') == -1 || m_mail.IndexOf('.') == -1)
                        {
                            EditorGUILayout.HelpBox("Missing valid mail.", MessageType.Error);

                            error = true;
                        }

                        GUI.enabled = !error;

                        if (GUILayout.Button("Send password reset mail"))
                        {
                            m_playFabHelper.ResetPassword(m_mail);

                            m_startScreenState = StartScreenState.Login;
                        }

                        GUI.enabled = true;
                    }
                    break;
            }
        }

        bool InitiateBuild(out Common.PublishInformation publishInfo)
        {
            bool buildRes = false;

            try
            {
                if (System.IO.Directory.Exists(ContentBuilder.TempBuildPath))
                {
                    System.IO.Directory.Delete(ContentBuilder.TempBuildPath, true);
                }

                System.IO.Directory.CreateDirectory(ContentBuilder.TempBuildPath);

                buildRes = ContentBuilder.BuildScene(m_levelDesc.SharedSettings.Title, m_levelDesc.SharedSettings.Description, 
                    (int)m_levelDesc.SharedSettings.MapEnvType, 
                    (int)m_levelDesc.SharedSettings.MapSize, 
                    (int)m_levelDesc.SharedSettings.TimeOfDay, 
                    m_levelDesc.SharedSettings.PublishedItemId, 
                    m_levelDesc.SharedSettings.DisplayVersion, 
                    null,
                    out publishInfo);
            }
            catch (System.Exception e)
            {
                publishInfo = default(Common.PublishInformation);

                EditorUtility.DisplayDialog("Error", e.Message + e.StackTrace, "OK");
            }

            return buildRes;
        }

        void PublishSubmission()
        {
            Common.PublishInformation publishInfo;

            if (InitiateBuild(out publishInfo))
            {
                m_playFabHelper.UploadAndPublish(
                    publishInfo,
                    ContentBuilder.FullThumbnailPath,
                    //ContentBuilder.FullAssetBundlePath,
                    UpdateItemId
                    );
            }
        }

        private void UpdateSubmission()
        {
            // Just rebuild and upload?
            Common.PublishInformation publishInfo;

            if (InitiateBuild(out publishInfo))
            {
                m_playFabHelper.UploadAndUpdate(
                    publishInfo,
                    ContentBuilder.FullThumbnailPath,
                    //ContentBuilder.FullAssetBundlePath,
                    null
                    );
            }
        }

        void ShowClickableLink(string url)
        {
            Color tmpColor = GUI.color;

            Color newColor;

            if (ColorUtility.TryParseHtmlString("#87CEFA", out newColor))
                GUI.color = newColor;

            if (GUILayout.Button(url, GUI.skin.label))
            {
                Application.OpenURL(url);
            }

            GUI.color = tmpColor;
        }

        IEnumerator DownloadImageAndCache(string url)
        {
            UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequestTexture.GetTexture(url);

            request.SendWebRequest();

            while (!request.isDone)
            {
                m_imageCache[url].progress = request.downloadProgress;

                Repaint();

                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
            }
            else
            {
                yield return null;

                m_imageCache[url].texture = ((UnityEngine.Networking.DownloadHandlerTexture)request.downloadHandler).texture;
            }
        }
    
        // Callbacks
        public void UpdateItemId(string id)
        {
            Onward.CustomContent.Assets.LevelDescriptor levelDesc = GameObject.FindObjectOfType<Onward.CustomContent.Assets.LevelDescriptor>();

            levelDesc.SharedSettings.PublishedItemId = id;

            EditorUtility.SetDirty(levelDesc);
            EditorUtility.SetDirty(levelDesc.SharedSettings);

            UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene());

            // Store the ID back into PlayFab

            m_playFabHelper.AddPublishedId(id);
        }

        public void OnPlayFabError(string message)
        {
            EditorUtility.ClearProgressBar();

            EditorUtility.DisplayDialog("PlayFab Error", message, "OK");

            Repaint();
        }

        public void OnPlayFabSuccess()
        {
            EditorUtility.ClearProgressBar();

            Repaint();
        }
    }
}
#endif