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

namespace Onward.CustomContent.EditorTools
{
    public class ContentBuilder : MonoBehaviour
    {
        // Setup platform specific stereo rendering settings
        static Dictionary<UnityEditor.BuildTarget, StereoRenderingPath> DictStereoRenderingPath = new Dictionary<BuildTarget, StereoRenderingPath>()
        {
            { BuildTarget.StandaloneWindows,        StereoRenderingPath.Instancing },
            { BuildTarget.StandaloneWindows64,      StereoRenderingPath.Instancing },

            { BuildTarget.Android,                  StereoRenderingPath.SinglePass }
        };

        static List<int> allocatedIds = new List<int>();
        static Assets.LevelDescriptor levelDescriptor;

        public static string FullAssetBundlePathForBuildTarget(BuildTarget buildTarget) => System.IO.Path.Combine(TempBuildPath, $"custom_{buildTarget.ToString()}.map");

        public static string GetAssetBundleName()       => $"custom_{UnityEditor.EditorUserBuildSettings.activeBuildTarget.ToString()}.map";

        public static readonly string ThumbnailName     = "thumbnail.png";

        public static readonly string TempBuildPath     = "TempUnityBuild";

        public static string FullAssetBundlePath
        {
            get => System.IO.Path.Combine(TempBuildPath, GetAssetBundleName());
        }

        public static string FullThumbnailPath
        {
            get => System.IO.Path.Combine(TempBuildPath, ThumbnailName);
        }

        public static bool BuildScene(string title, string desc, int envType, int mapSize, int timeOfDay, string publishedItemId, string displayVersion, BuildTarget? restrictToPlatform,
           out Common.PublishInformation publishInfo)
        {
            publishInfo = new Common.PublishInformation();

            if (UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().isDirty)
            {
                if (!UnityEditor.EditorUtility.DisplayDialog(
                    "Save scene and build?",
                    "To continue in the build process your scene will be saved.\n\nAre you okay with that?",
                    "OK", "Cancel"))
                {
                    return false;
                }
            }

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

            if (levelDescriptor == null)
            {
                levelDescriptor = GameObject.FindObjectOfType<Onward.CustomContent.Assets.LevelDescriptor>();
            }

            if (levelDescriptor == null || levelDescriptor.SharedSettings == null)
            {
                throw new System.Exception("You need to create and setup shared settings for your scene.");
            }

            List<Onward.CustomContent.SharedLevelSettings.SceneData> scenes = levelDescriptor.SharedSettings.GetSceneList();

            if (scenes.Count == 0)
            {
                throw new System.Exception("You have no scenes assigned in shared settings to build.");
            }


          
            
            
            
            CreateThumbnail(System.IO.Path.Combine(TempBuildPath, ThumbnailName));

            foreach (var s in scenes)
            {
                if (restrictToPlatform.HasValue && s.TargetPlatform != restrictToPlatform)
                {
                    continue;
                }

                UnityEditor.SceneManagement.EditorSceneManager.OpenScene(UnityEditor.AssetDatabase.GetAssetPath(s.Asset));

                EditorUserBuildSettings.SwitchActiveBuildTarget(s.TargetGroup, s.TargetPlatform);

                if (!DictStereoRenderingPath.TryGetValue(s.TargetPlatform, out var stereoRenderingPath))
                {
                    throw new System.Exception($"Missing stereo rendering path for {s.TargetPlatform}");
                }

                Debug.Log($"Setting stereo rendering path to {stereoRenderingPath}");

                PlayerSettings.stereoRenderingPath = stereoRenderingPath;

                // Platform switch might reload scripting domain. We need to make sure our reference remains valid.
                if (levelDescriptor == null)
                {
                    levelDescriptor = GameObject.FindObjectOfType<Onward.CustomContent.Assets.LevelDescriptor>();
                }

                VerifyAndPrepare();

                // Remove all the PlayFab "singleton"s
                PlayFab.Internal.PlayFabHttp[] httpObjs = GameObject.FindObjectsOfType<PlayFab.Internal.PlayFabHttp>();

                for (int i = 0; i < httpObjs.Length; ++i)
                    GameObject.DestroyImmediate(httpObjs[i].gameObject);

                // Serialize AI information
                Onward.AI.Cover.CoverManager aiCoverManager = GameObject.FindObjectOfType<Onward.AI.Cover.CoverManager>();
                Onward.AI.Navigation.NavigationManager aiNavManager = GameObject.FindObjectOfType<Onward.AI.Navigation.NavigationManager>();

                // Wipe existing stuff
                levelDescriptor.AI_CoverBake = "";
                levelDescriptor.AI_NavBake = "";

                if (aiCoverManager != null && aiCoverManager.Data != null)
                {
                    levelDescriptor.AI_CoverBake = Onward.AI.Cover.CoverUtilities.ConvertScriptableObjectToJson(aiCoverManager.Data);
                }

                if (aiNavManager != null && aiNavManager.Data != null)
                {
                    levelDescriptor.AI_NavBake = Onward.AI.Navigation.NavigationUtilities.ConvertScriptableObjectToJson(aiNavManager.Data);
                }

                // Serialize Physics Material information
                Assets.SetPhysicMaterial[] physMats = GameObject.FindObjectsOfType<Assets.SetPhysicMaterial>();

                levelDescriptor.CachedPhysMats = new List<Assets.LevelDescriptor.CachedPhysMat>(physMats.Length);

                for (int i = 0; i < physMats.Length; ++i)
                {
                    Assets.LevelDescriptor.CachedPhysMat cachedCollision = new Assets.LevelDescriptor.CachedPhysMat();

                    cachedCollision.SetPhysMat = physMats[i];
                    cachedCollision.Colliders = physMats[i].IncludeChildren ? physMats[i].GetComponentsInChildren<Collider>() : physMats[i].GetComponents<Collider>();

                    levelDescriptor.CachedPhysMats.Add(cachedCollision);
                }

                UnityEditor.EditorUtility.SetDirty(levelDescriptor);

                // Save
                UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());

                Onward.CustomContent.Assets.GM_Base[] gameModes = GameObject.FindObjectsOfType<Onward.CustomContent.Assets.GM_Base>();

                List<string> supportedGameModes = new List<string>(gameModes.Length);

                for (int i = 0; i < gameModes.Length; ++i)
                {
                    string str = ((int)gameModes[i].GameModeType).ToString();

                    supportedGameModes.Add(str);
                }

                publishInfo = new Common.PublishInformation
                {
                    title = title,
                    description = desc,

                    //tags = new[] { "map" },

                    env_type = envType.ToString(),
                    map_size = mapSize.ToString(),
                    time_of_day = timeOfDay.ToString(),

                    pp_profile = ((int)levelDescriptor.SharedSettings.PPProfileId).ToString(),

                    game_modes = supportedGameModes.ToArray(),

                    unity_version = Application.unityVersion,
                    sdk_version = Onward.CustomContent.Global.SdkVersion,

                    published_id = publishedItemId.Trim(),
                    version_notes = "",
                    display_version = displayVersion.Trim(),

                    platforms = publishInfo.platforms,
                    bundlePaths = publishInfo.bundlePaths,
                    bundle_hash = publishInfo.bundle_hash
                };

                AddTags(publishInfo, levelDescriptor);

                bool buildRes = Build(s.TargetPlatform, publishInfo);

                if (!buildRes)
                {
                    return false;
                }
            }

            // Reload scene
            UnityEditor.SceneManagement.EditorSceneManager.OpenScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().path);

            return true;
        }

        public static string CreateHumanReadableGameModeString(Onward.CustomContent.Assets.GM_Base.EGameModeType mode)
        {
            switch (mode)
            {
                case Assets.GM_Base.EGameModeType.Uplink:
                    return "Uplink";

                case Assets.GM_Base.EGameModeType.Assault:
                    return "Assault";

                case Assets.GM_Base.EGameModeType.Escort:
                    return "Escort";

                case Assets.GM_Base.EGameModeType.Operations_Evac:
                case Assets.GM_Base.EGameModeType.Operations_Hunt:
                    return "Operations";
            }

            return "Social";
        }

        static void AddTags(Common.PublishInformation info, Onward.CustomContent.Assets.LevelDescriptor levelDescriptor)
        {
            List<string> tags = new List<string>();

            tags.Add("Map");

            for (int i = 0; i < info.game_modes.Length; ++i)
            {
                Onward.CustomContent.Assets.GM_Base.EGameModeType gameMode = (Onward.CustomContent.Assets.GM_Base.EGameModeType) int.Parse(info.game_modes[i]);

                tags.Add(CreateHumanReadableGameModeString(gameMode));
            }

            Onward.CustomContent.Assets.LevelDescriptor.EMapEnvironment envType = (Onward.CustomContent.Assets.LevelDescriptor.EMapEnvironment)int.Parse(info.env_type);
            Onward.CustomContent.Assets.LevelDescriptor.EMapSize mapSize = (Onward.CustomContent.Assets.LevelDescriptor.EMapSize)int.Parse(info.map_size);
            Onward.CustomContent.Assets.LevelDescriptor.ETimeOfDay timeOfDay = (Onward.CustomContent.Assets.LevelDescriptor.ETimeOfDay)int.Parse(info.time_of_day);

            tags.Add(envType.ToString());
            tags.Add(mapSize.ToString());
            tags.Add(timeOfDay.ToString());

            tags.Add(Global.TagUnityVersion);

            if (levelDescriptor.SharedSettings.Scene_PC != null)
            {
                tags.Add(Global.TagPcPlatform);
            }

            if (levelDescriptor.SharedSettings.Scene_Quest != null)
            {
                tags.Add(Global.TagAndroidPlatform);
            }

            // Remove duplicates and assign
            info.tags = tags.Distinct().ToArray();
        }

        static bool Build(BuildTarget buildTarget, Common.PublishInformation publishInformation)
        {
            try
            {
                Camera[] cameras = GameObject.FindObjectsOfType<Camera>();

                // Set camera clear flags and color. The changes are only made for the build process and reverted after.
                cameras[0].clearFlags = CameraClearFlags.Color;
                cameras[0].backgroundColor = Color.black;
                cameras[0].cullingMask = 0;

                RemoveAssetsOfType<UnityEngine.EventSystems.EventSystem>();

                RemoveAssetsOfType<UnityEngine.EventSystems.BaseInputModule>();
                RemoveAssetsOfType<UnityEngine.EventSystems.BaseInput>();

                AssetBundleManifest manifest = BuildBundle(buildTarget, TempBuildPath, GetBundlesForBuild());

                publishInformation.bundle_hash.Add(manifest.GetAssetBundleHash(manifest.GetAllAssetBundles()[0]).ToString());
                publishInformation.platforms.Add(PlayFabUtils.GetTargetPlatformName());
                publishInformation.bundlePaths.Add(FullAssetBundlePath);

                //CreateThumbnail(System.IO.Path.Combine(TempBuildPath, ThumbnailName));
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.Message + "\n" + e.StackTrace);

                return false;
            }

            return true;
        }

        static void RemoveAssetsOfType<T>() where T : UnityEngine.Object
        {
            T[] assetsOfType = GameObject.FindObjectsOfType<T>();

            foreach (T asset in assetsOfType)
            {
                DestroyImmediate(asset);
            }
        }

        public static void VerifyAndPrepare()
        {
            List<ContentException> collectedErrors = new List<ContentException>();

            // TODO: Collect all errors and throw a single exception that contains all errors that have been detected so far.
            levelDescriptor = GameObject.FindObjectOfType<Assets.LevelDescriptor>();

            if (levelDescriptor == null)
            {
                collectedErrors.Add(new ContentExceptionMissingLevel());
            }

            if (levelDescriptor != null && levelDescriptor.SharedSettings == null)
            {
                collectedErrors.Add(new CustomContent.ContentException($"Missing {nameof(SharedLevelSettings)} for LevelDescriptor"));
            }

            if (GameObject.FindObjectOfType<Assets.Tent>() == null)
            {
                collectedErrors.Add(new CustomContent.ContentException("Tent is a requirement."));
            }

            if (GameObject.FindObjectOfType<Assets.GM_FreeRoam>() == null)
            {
                collectedErrors.Add(new CustomContent.ContentException("Game mode free roam is a requirement."));
            }

            if (GameObject.FindObjectsOfType<Assets.GM_Base>().Length < 2)
            {
                collectedErrors.Add(new CustomContent.ContentException("In need of at least one more game mode beside free roam."));
            }

            if (GameObject.FindObjectOfType<Assets.MapQuad>() == null)
            {
                collectedErrors.Add(new CustomContent.ContentException("Please add the Map Quad prefab (required for the minimap)."));
            }

            if (GameObject.FindObjectsOfType<Camera>().Length == 0)
            {
                collectedErrors.Add(new CustomContent.ContentException("At least one camera is required for the scene to function properly."));
            }

            if (!PlayerSettings.virtualRealitySupported)
            {
                collectedErrors.Add(new CustomContent.ContentException("You have Virtual reality setting not enabled"));
            }

            if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass)
            {
                collectedErrors.Add(new CustomContent.ContentException("stereo rendering mode is not Single pass!"));
            }
            
            if (PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup) != ScriptingImplementation.IL2CPP)
            {
                collectedErrors.Add(new CustomContent.ContentException("Scripting Backend is not set to IL2CPP!"));
            }

            AudioSource[] foundAudioSources = GameObject.FindObjectsOfType<AudioSource>();
            foreach (AudioSource audioSource in foundAudioSources)
            {
                if (audioSource != null)
                    collectedErrors.Add(new CustomContent.ContentException(audioSource.gameObject.name + " - Unity's AudioSource is not supported. Please use OnwardAudioSource with the audio provided instead.", audioSource.gameObject));
            }

            // Performance checks
            {
                Light[] allLights = GameObject.FindObjectsOfType<Light>();

                int directionalLights = 0;

                foreach (Light light in allLights)
                {
                    if (light.type == LightType.Directional)
                    {
                        ++directionalLights;

                        if (light.lightmapBakeType == LightmapBakeType.Mixed || light.lightmapBakeType == LightmapBakeType.Baked)
                        {
                            // Thats alright
                        }
                        else
                        {
                            collectedErrors.Add(new CustomContent.ContentExceptionWithGameObject(light.gameObject, "Directional Light needs to be set to Baked or Mixed."));
                        }
                    }
                    else
                    {
                        if (light.lightmapBakeType != LightmapBakeType.Baked)
                        {
                            collectedErrors.Add(new CustomContent.ContentExceptionWithGameObject(light.gameObject, "Lights need to be baked."));
                        }
                    }
                }

                if (directionalLights != 1)
                {
                    collectedErrors.Add(new CustomContent.ContentException("Your map needs to feature exactly one Directional Light."));
                }

                if (LightmapSettings.lightmaps.Length <= 0)
                {
                    collectedErrors.Add(new CustomContent.ContentException("Baked lightmap required."));
                }
            }


            if (collectedErrors.Count != 0)
            {
                // Combine all eror messages

                System.Text.StringBuilder sbErrorMsg = new System.Text.StringBuilder();

                sbErrorMsg.Append($"Errors have been found. This is a combined report of all of them:{System.Environment.NewLine}{System.Environment.NewLine}");

                foreach (ContentException ex in collectedErrors)
                {
                    sbErrorMsg.Append($"[*] {ex.Message}{System.Environment.NewLine}{System.Environment.NewLine}");
                }

                sbErrorMsg.Append($"Errors: {collectedErrors.Count}");

                EditorUtility.DisplayDialog("Errors found :-(", sbErrorMsg.ToString(), "OK");

                throw new ContentException(sbErrorMsg.ToString());
            }

            Assets.Entity[] allEntities = GameObject.FindObjectsOfType<Assets.Entity>();

            // Enforcing a consistent sorting order. Just in case.
            allEntities = allEntities.OrderBy(m => m.transform.position.y).ThenBy(m => m.transform.position.x).ThenBy(m => m.transform.position.z).ToArray();

            PrepareScene(allEntities);
        }

        static void PrepareScene(Assets.Entity[] entities)
        {
            allocatedIds.Clear();

            for (int i = 0; i < entities.Length; ++i)
            {
                int new_id = GenerateId();

                entities[i].SetId(new_id);

                entities[i].Validate();
            }
        }

        static int GenerateId()
        {
            int[] ReservedIds = { };

            int newId = -1;

            do
            {
                newId = allocatedIds.Count + 1;

                allocatedIds.Add(newId);
            } while (ReservedIds.Contains(newId));

            return newId;
        }

        static List<AssetBundleBuild> GetBundlesForBuild()
        {
            List<AssetBundleBuild> assetBundleBuilds = new List<AssetBundleBuild>();

            UnityEngine.SceneManagement.Scene activeScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();

            AssetBundleBuild currentScene = new AssetBundleBuild
            {
                assetBundleName = GetAssetBundleName(),
                assetNames = new[] { activeScene.path }
            };

            assetBundleBuilds.Add(currentScene);

            return assetBundleBuilds;
        }

        static AssetBundleManifest BuildBundle(BuildTarget buildTarget, string path, List<AssetBundleBuild> builds)
        {
            if (builds.Count <= 0)
                throw new ContentException("Nothing to build. Make sure your scene is assigned to an asset bundle.");

            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            Debug.Log($"Building for platform {buildTarget}");

            AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(path, builds.ToArray(), 
                BuildAssetBundleOptions.ChunkBasedCompression,
                buildTarget
                );

            if (manifest.GetAllAssetBundles().Length <= 0)
                throw new ContentException("Manifest is missing bundles.");

            return manifest;
        }

        static void CreateThumbnail(string path)
        {
            // Normally this would be an error but we might also build for a local test
            if (levelDescriptor.SharedSettings.Thumbnail == null)
            {
                return;
            }

            Texture2D t2d = levelDescriptor.SharedSettings.Thumbnail as Texture2D;

            string assetPath = AssetDatabase.GetAssetPath(t2d);

            TextureImporter tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;

            if (tImporter != null)
            {
                tImporter.isReadable = true;
                tImporter.textureCompression = TextureImporterCompression.Uncompressed;

                AssetDatabase.ImportAsset(assetPath);
                AssetDatabase.Refresh();
            }

            if (!t2d.isReadable)
                throw new ContentException("Thumbnail not readable!");

            System.IO.File.WriteAllBytes(path, t2d.EncodeToPNG());
        }
    }
#endif
}