﻿#if UNITY_EDITOR

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Diagnostics;

namespace Onward.CustomContent.EditorTools
{
    public class OnwardLauncher : EditorWindow
    {
        const string PrefBinPath = "_ONWARD_BIN_PATH_";
        const string PrefLaunchGame = "_ONWARD_LAUNCH_GAME_";
        const string PrefPlatform = "_ONWARD_PLATFORM_";

        bool ToggleLaunchGame
        {
            get => EditorPrefs.GetBool(PrefLaunchGame, true);
            set => EditorPrefs.SetBool(PrefLaunchGame, value);
        }

        string BinPath
        {
            get => EditorPrefs.GetString(PrefBinPath, "%appdata%/../LocalLow/Downpour Interactive/Onward/CustomContent");
            set => EditorPrefs.SetString(PrefBinPath, value);
        }

        int ActivePlatform
        {
            get => EditorPrefs.GetInt(PrefPlatform, 0);
            set => EditorPrefs.SetInt(PrefPlatform, value);
        }

        [MenuItem("ONWARD/Onward Launcher")]
        public static void ShowLauncherWindow()
        {
            GetWindow<OnwardLauncher>(false, "Onward Launcher", true);
        }

        const int PlatformPC = 0;
        const int PlatformQuest = 1;

        string[] options = new string[]
        {
            "PC",
            "Quest"
        };

        private void OnGUI()
        {
            ActivePlatform = EditorGUILayout.Popup("Platform", ActivePlatform, options);

            GUILayout.Space(20);

            switch (ActivePlatform)
            {
                case PlatformPC:
                    PC();
                    break;

                case PlatformQuest:
                    Quest();
                    break;
            }

            void PC()
            {
                GUILayout.Label("Path to PC Custom Content folder:");

                GUILayout.BeginHorizontal();

                BinPath = System.Environment.ExpandEnvironmentVariables(GUILayout.TextField(BinPath));

                if (GUILayout.Button("...", GUILayout.Width(35)))
                {
                    BinPath = EditorUtility.OpenFolderPanel("Select Custom Content folder", BinPath, "");
                }

                GUILayout.EndHorizontal();

                //Dieser PC\Quest\Interner gemeinsamer Speicher\Android\data\com.downpourinteractive.onward\files\CustomContent
                GUILayout.Label(@"The path should look like: C:\Users\YourUserName\AppData\LocalLow\Downpour Interactive\Onward\CustomContent");

                //ToggleLaunchGame = GUILayout.Toggle(ToggleLaunchGame, "Launch game after build");

                GUI.enabled = (BinPath.Length > 0 && System.IO.Directory.Exists(BinPath));

                if (GUILayout.Button("Build"))
                {
                    Common.PublishInformation info;

                    if (ContentBuilder.BuildScene("Launcher", "Launcher",
                        (int)Onward.CustomContent.Assets.LevelDescriptor.EMapEnvironment.Desert,
                        (int)Onward.CustomContent.Assets.LevelDescriptor.EMapSize.Medium,
                        (int)Onward.CustomContent.Assets.LevelDescriptor.ETimeOfDay.Day,
                        "",
                        "",
                        BuildTarget.StandaloneWindows64,
                        out info))
                    {
                        string bundlePath = System.IO.Path.Combine(Application.dataPath + "/../", ContentBuilder.FullAssetBundlePath)
                            .Replace('/', '\\');

                        Onward.CustomContent.PlayFabUtils.ItemDisplayProperties displayProps = new PlayFabUtils.ItemDisplayProperties();

                        displayProps.hash = "<local>";

                        Onward.CustomContent.Assets.GM_Base[] allModes = GameObject.FindObjectsOfType<Onward.CustomContent.Assets.GM_Base>();
                        List<string> modes = new List<string>();

                        for (int i = 0; i < allModes.Length; ++i)
                            modes.Add(((int)allModes[i].GameModeType).ToString());

                        displayProps.game_modes = modes.ToArray();

                        string filename = "unity-export";

                        // Copy to final location
                        System.IO.File.Copy(bundlePath, System.IO.Path.Combine(BinPath, $"{filename}.local.content2"), true);
                        System.IO.File.WriteAllText(System.IO.Path.Combine(BinPath, $"{filename}.local.info2"), UnityEngine.JsonUtility.ToJson(displayProps));

                        UnityEditor.EditorUtility.DisplayDialog("Success!", "Map should be locally available in Onward now!\n\nMap name: Unity Export", "OK");
                    }
                }

                GUI.enabled = true;
            }

            void Quest()
            {
                if (GUILayout.Button("Build"))
                {
                    BinPath = EditorUtility.SaveFolderPanel("Build destination", "Destination", "");

                    Common.PublishInformation info;

                    if (ContentBuilder.BuildScene("Launcher", "Launcher",
                        (int)Onward.CustomContent.Assets.LevelDescriptor.EMapEnvironment.Desert,
                        (int)Onward.CustomContent.Assets.LevelDescriptor.EMapSize.Medium,
                        (int)Onward.CustomContent.Assets.LevelDescriptor.ETimeOfDay.Day,
                        "",
                        "",
                        BuildTarget.Android,
                        out info))
                    {
                        string bundlePath = System.IO.Path.Combine(Application.dataPath + "/../", ContentBuilder.FullAssetBundlePath)
                            .Replace('/', '\\');

                        Onward.CustomContent.PlayFabUtils.ItemDisplayProperties displayProps = new PlayFabUtils.ItemDisplayProperties();

                        displayProps.hash = "<local>";

                        Onward.CustomContent.Assets.GM_Base[] allModes = GameObject.FindObjectsOfType<Onward.CustomContent.Assets.GM_Base>();
                        List<string> modes = new List<string>();

                        for (int i = 0; i < allModes.Length; ++i)
                            modes.Add(((int)allModes[i].GameModeType).ToString());

                        displayProps.game_modes = modes.ToArray();

                        string filename = "unity-export";

                        string contentFile = System.IO.Path.Combine(BinPath, $"{filename}.local.content2");

                        // Copy to final location
                        System.IO.File.Copy(bundlePath, contentFile, true);
                        System.IO.File.WriteAllText(System.IO.Path.Combine(BinPath, $"{filename}.local.info2"), UnityEngine.JsonUtility.ToJson(displayProps));

                        EditorUtility.RevealInFinder(contentFile);

                        UnityEditor.EditorUtility.DisplayDialog("Success!", "Copy both files to your device.\n\nPath:\nThis PC\\Quest\\Internal Storage\\Android\\data\\com.downpourinteractive.onward\\files\\CustomContent", "OK");
                    }
                }
            }
        }
    }
}

#endif