﻿#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine.UI;

public class AdvertyObject
{
    public AdvertyObject(string scenePath, string objectName, string objectPath, GameObject obj)
    {
        ScenePath = scenePath;
        ObjectName = objectName;
        ObjectPath = objectPath;
        Obj = obj;
    }

    public string ScenePath { get; set; }
    public string SceneName
    {
        get {
            return ScenePath?.Split('/').Last().Split('.').First();
        }
    }
    public string ObjectName { get; set; }
    public string ObjectPath { get; set; }
    public GameObject Obj { get; set; }
}

public class AdvertyUpgrade4to5 : EditorWindow
{
    private Vector2 scrollPos;
    private List<AdvertyObject> foundObjectsInScenes = new List<AdvertyObject>();
    private List<AdvertyObject> updatedObjectsInScenes = new List<AdvertyObject>();
    private bool showUpdated = false;
    private bool shadersCopied = false;

    private static string InPlayUnitName = "Adverty.InPlayUnit";
    private string InMenuUnitName = "Adverty.InMenuUnit";
    private string meshUnitRendererName = "Adverty.AdUnit.Renderer.MeshUnitRenderer";
    private string spriteUnitRendererName = "Adverty.AdUnit.Renderer.SpriteUnitRenderer";
    private string uiUnitRendererName = "Adverty.AdUnit.Renderer.UIUnitRenderer";
    private string inMenuUnitClickHandlerName = "InMenuUnitClickHandler";

    [MenuItem("Tools/Upgrade Adverty plugin", true)]
    private static bool ShowFindUnitsMenu()
    {
        return FindTypeByName(InPlayUnitName) != null;
    }

    [MenuItem("Tools/Upgrade Adverty plugin")]
    public static void ShowWindow()
    {
        GetWindow<AdvertyUpgrade4to5>("Find Adverty Units");
    }

    private void OnGUI()
    {
        GUILayout.Label("Find and Replace Ad Units", EditorStyles.boldLabel);

        if (GUILayout.Button("Find Ad Units Objects"))
        {
            FindObjectsInAllScenes();
            showUpdated = false;
        }

        if (!showUpdated)
        {
            if (foundObjectsInScenes.Count > 0)
            {
                if (GUILayout.Button("Update Ad Units Objects"))
                {
                    updatedObjectsInScenes.Clear();
                    ReplaceComponentInFoundItems(InPlayUnitName);
                    ReplaceComponentInFoundItems(InMenuUnitName);
                    foundObjectsInScenes.Clear();
                    showUpdated = true;
                }
            }
        }

        GUILayout.Space(10);
        int count = showUpdated ? updatedObjectsInScenes.Count : foundObjectsInScenes.Count;
        GUILayout.Label(showUpdated ? "Update Items complete: " + count : "Found Items: " + count,
                        EditorStyles.boldLabel);

        scrollPos = GUILayout.BeginScrollView(scrollPos);

        List<AdvertyObject> list = showUpdated ? updatedObjectsInScenes : foundObjectsInScenes;

        for (int i = 0; i < list.Count; i++)
        {
            string buttonLabel =
                string.Format("{0}/{1} ({2})", list[i].SceneName, list[i].ObjectName, list[i].ObjectPath);

            if (GUILayout.Button(buttonLabel, GUILayout.ExpandWidth(true)))
            {
                EditorGUIUtility.PingObject(list[i].Obj);
                Selection.activeObject = list[i].Obj;
            }
        }

        GUILayout.EndScrollView();
    }

    private void FindObjectsInAllScenes()
    {
        foundObjectsInScenes.Clear();

        string[] scenePaths = AssetDatabase.FindAssets("t:Scene").Select(AssetDatabase.GUIDToAssetPath).ToArray();
        foreach (string scenePath in scenePaths)
        {
            if (scenePath.StartsWith("Assets/Adverty/Example"))
            {
                continue;
            }

            if (!IsSceneInReadOnlyPackage(scenePath))
            {
                Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
                GameObject[] rootObjects = scene.GetRootGameObjects();
                int currentObjectsCount = foundObjectsInScenes.Count;
                foreach (GameObject obj in rootObjects)
                {
                    FindObjectsWithScript(obj, InPlayUnitName, scenePath);
                    FindObjectsWithScript(obj, InMenuUnitName, scenePath);
                }
                if (currentObjectsCount == foundObjectsInScenes.Count)
                {
                    EditorSceneManager.CloseScene(scene, true);
                }
            }
        }
    }

    private static bool IsSceneInReadOnlyPackage(string scenePath)
    {
        return !string.IsNullOrEmpty(scenePath) && scenePath.StartsWith("Packages");
    }

    private void FindObjectsWithScript(GameObject obj, string scriptName, string scenePath, string parentPath = "")
    {
        System.Type scriptType = FindTypeByName(scriptName);
        if (scriptType != null)
        {
            MonoBehaviour script = (MonoBehaviour)obj.GetComponent(scriptType);
            string uniquePath = string.IsNullOrEmpty(parentPath) ? obj.name : parentPath + "/" + obj.name;

            if (script != null)
            {
                foundObjectsInScenes.Add(new AdvertyObject(scenePath, obj.name, uniquePath, obj));
            }
        }

        for (int i = 0; i < obj.transform.childCount; i++)
        {
            FindObjectsWithScript(obj.transform.GetChild(i).gameObject, scriptName, scenePath,
                                  parentPath + "/" + obj.name);
        }
    }

    private bool ObjectHasComponent(GameObject obj, string componentName)
    {
        System.Type componentType = FindTypeByName(componentName);
        if (componentType != null)
        {
            MonoBehaviour[] scripts = obj.GetComponentsInChildren(componentType, true).Cast<MonoBehaviour>().ToArray();
            if (scripts.Length > 0)
            {
                return true;
            }
        }
        return false;
    }

    private void ReplaceComponentInFoundItems(string scriptName)
    {
        System.Type oldComponentType = FindTypeByName(scriptName);

        if (oldComponentType == null || !typeof(MonoBehaviour).IsAssignableFrom(oldComponentType))
        {
            Debug.LogError($"Old component '{InPlayUnitName}' not found or does not derive from MonoBehaviour.");
            return;
        }

        for (int i = 0; i < foundObjectsInScenes.Count; i++)
        {
            AdvertyObject foundObject = foundObjectsInScenes[i];

            if (!ObjectHasComponent(foundObject.Obj, scriptName))
            {
                continue;
            }

            Scene scene = EditorSceneManager.OpenScene(foundObject.ScenePath, OpenSceneMode.Additive);
            GameObject obj = foundObject.Obj;

            if (obj != null)
            {
                EditorUtility.DisplayProgressBar("Updating Ad Units",
                                                 $"Processing {foundObject.SceneName}/{foundObject.ObjectName}",
                                                 (float)i / foundObjectsInScenes.Count);

                GameObject prefabInstance = GetPrefabObject(obj);
                if (prefabInstance != null)
                {
                    UpdatePrefab(prefabInstance, scriptName, oldComponentType);
                }

                ReplaceComponent(obj, oldComponentType);

                EditorSceneManager.MarkSceneDirty(scene);
                EditorSceneManager.SaveScene(scene);
                updatedObjectsInScenes.Add(foundObject);
            }
        }

        EditorUtility.ClearProgressBar();
    }

    public GameObject GetPrefabObject(GameObject gameObject)
    {
        if (gameObject == null)
        {
            return null;
        }

        if (PrefabUtility.GetPrefabInstanceStatus(gameObject) != PrefabInstanceStatus.NotAPrefab)
        {
            return PrefabUtility.GetCorrespondingObjectFromOriginalSource(
                PrefabUtility.GetNearestPrefabInstanceRoot(gameObject));
        }

        Transform currentTransform = gameObject.transform.parent;
        while (currentTransform != null)
        {
            if (PrefabUtility.GetPrefabInstanceStatus(currentTransform.gameObject) != PrefabInstanceStatus.NotAPrefab)
            {
                return PrefabUtility.GetCorrespondingObjectFromOriginalSource(
                    PrefabUtility.GetNearestPrefabInstanceRoot(currentTransform.gameObject));
            }
            currentTransform = currentTransform.parent;
        }

        return null;
    }

    private void UpdatePrefab(GameObject prefab, string scriptName, System.Type oldComponentType)
    {
        if (prefab != null)
        {
            if (!ObjectHasComponent(prefab, scriptName))
            {
                return;
            }

            string assetPath = AssetDatabase.GetAssetPath(prefab);

            if (string.IsNullOrEmpty(assetPath))
            {
                return;
            }

            string pathPattern = "^Assets/Adverty/.*";

            if (Regex.IsMatch(assetPath, pathPattern))
            {
                string[] dependencies = AssetDatabase.GetDependencies(assetPath);

                foreach (string dependency in dependencies)
                {
                    if (dependency == assetPath)
                    {
                        continue;
                    }

                    if (Regex.IsMatch(dependency, pathPattern))
                    {
                        if (!dependency.Contains(".dll") && !dependency.Contains(".cs"))
                        {
                            CopyResource(dependency);
                        }
                    }
                }

                CopyResource(assetPath);
            }

            MonoBehaviour[] scripts =
                prefab.GetComponentsInChildren(oldComponentType, true).Cast<MonoBehaviour>().ToArray();
            foreach (MonoBehaviour s in scripts)
            {
                ReplaceComponent(s.gameObject, oldComponentType);
            }

            PrefabUtility.SavePrefabAsset(prefab);
        }
    }

    private void ReplaceComponent(GameObject obj, System.Type oldComponentType)
    {
        ReplaceRenderer(obj, FindTypeByName(meshUnitRendererName), typeof(Adverty5.AdPlacements.MeshAdPlacement));
        ReplaceRenderer(obj, FindTypeByName(spriteUnitRendererName), typeof(Adverty5.AdPlacements.SpriteAdPlacement));
        RemoveScript(obj, FindTypeByName(inMenuUnitClickHandlerName));

        if (ReplaceRenderer(obj, FindTypeByName(uiUnitRendererName), typeof(Adverty5.AdPlacements.UIAdPlacement)))
        {
            obj.AddComponent<Adverty5.AdPlacements.ClickablePlacementUIComponent>();
        }
        MonoBehaviour oldComponent = obj.GetComponent(oldComponentType) as MonoBehaviour;

        if (oldComponent != null)
        {
            DestroyImmediate(oldComponent, true);
        }
        CopyResources(obj);
    }

    private void CopyResources(GameObject obj)
    {
        try
        {
            Renderer renderer = obj.GetComponent<Renderer>();
            RawImage rawImage = obj.GetComponent<RawImage>();

            if (renderer == null && rawImage == null)
            {
                return;
            }

            Material material = null;

            if (renderer != null)
            {
                renderer.hideFlags = HideFlags.None;
                material = renderer.sharedMaterial;
            }

            if (rawImage != null)
            {
                rawImage.hideFlags = HideFlags.None;
                material = rawImage.material;
            }

            if (material == null)
            {
                return;
            }

            string assetPath = AssetDatabase.GetAssetPath(material);

            if (assetPath.StartsWith("Assets/Adverty/Resources/Materials"))
            {
                CopyResource(assetPath);
            }

            if (material.mainTexture != null)
            {
                string texturePath = AssetDatabase.GetAssetPath(material.mainTexture);
                if (texturePath.StartsWith("Assets/Adverty/Textures"))
                {
                    CopyResource(texturePath);
                }
            }

            if (material.shader != null)
            {
                string shaderPath = AssetDatabase.GetAssetPath(material.shader);
                if (shaderPath.StartsWith("Assets/Adverty/Resources/Shaders"))
                {
                    CopyResource(shaderPath);
                }
            }

            MeshFilter filter;
            if (obj.TryGetComponent(out filter))
            {
                Mesh mesh = filter.sharedMesh;
                string meshPath = AssetDatabase.GetAssetPath(mesh);

                if (meshPath.StartsWith("Assets/Adverty/Resources/Meshes"))
                {
                    CopyResource(meshPath);
                }
            }

            if (rawImage != null)
            {
                Texture texture = rawImage.texture;
                if (texture != null)
                {
                    string texturePath = AssetDatabase.GetAssetPath(texture);

                    if (texturePath.StartsWith("Assets/Adverty/Textures"))
                    {
                        CopyResource(texturePath);
                    }
                }
            }
        }
        catch (System.Exception e)
        {
            Debug.LogException(e);
        }
    }

    private void CopyResource(string assetPath)
    {
        string assetName = Path.GetFileName(assetPath);
        string assetFolder = Path.GetDirectoryName(assetPath);
        string newFolderPath = assetFolder.Replace("Adverty", "Adverty5/LegacyResources");
        string newAssetPath = Path.Combine(newFolderPath, assetName);

        if (!Directory.Exists("Assets/Adverty5/LegacyResources"))
        {
            Directory.CreateDirectory("Assets/Adverty5/LegacyResources");
            if (!Directory.Exists("Assets/Adverty5/LegacyResources/Resources"))
            {
                Directory.CreateDirectory("Assets/Adverty5/LegacyResources/Resources");
            }
            AssetDatabase.Refresh();
        }

        if (!shadersCopied && assetPath.StartsWith("Assets/Adverty/Resources/Shaders"))
        {
            if (Directory.Exists(assetFolder))
            {
                Directory.Move(assetFolder, newFolderPath);
                shadersCopied = true;
            }
            return;
        }

        if (!Directory.Exists(newFolderPath))
        {
            Directory.CreateDirectory(newFolderPath);
            AssetDatabase.Refresh();
        }

        if (!File.Exists(newAssetPath))
        {
            Debug.Log(string.Format("Copy Asset: {0} to {1}", assetPath, newAssetPath));

            string errorMessage = AssetDatabase.MoveAsset(assetPath, newAssetPath);
            if (!string.IsNullOrEmpty(errorMessage))
            {
                Debug.LogError(errorMessage);
            }

            if (newAssetPath.Contains(".png"))
            {
                UpdateTexture(newAssetPath);
            }

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

    private void UpdateTexture(string path)
    {
        try
        {
            TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;
            if (importer != null)
            {
                importer.isReadable = true;

                TextureImporterPlatformSettings textureSettings = importer.GetDefaultPlatformTextureSettings();
                textureSettings.textureCompression = TextureImporterCompression.Uncompressed;
                textureSettings.format = TextureImporterFormat.RGBA32;
                importer.SetPlatformTextureSettings(textureSettings);

                ChangeTextureFormat(importer, "Standalone");
                ChangeTextureFormat(importer, "Android");
                ChangeTextureFormat(importer, "iPhone");

                Debug.Log("Texture " + path + " format changed to RGBA32 and saved.");
            }
        }
        catch (System.Exception e)
        {
            Debug.LogException(e);
        }
    }

    private void ChangeTextureFormat(TextureImporter importer, string platform)
    {
        TextureImporterPlatformSettings textureSettings = importer.GetPlatformTextureSettings(platform);
        textureSettings.textureCompression = TextureImporterCompression.Uncompressed;
        textureSettings.format = TextureImporterFormat.RGBA32;
        importer.SetPlatformTextureSettings(textureSettings);
    }

    private bool ReplaceRenderer(GameObject obj, System.Type oldComponentType, System.Type newComponentType)
    {
        Component renderer = obj.GetComponent(oldComponentType);
        if (renderer != null)
        {
            DestroyImmediate(renderer, true);
            return obj.AddComponent(newComponentType);
        }
        return false;
    }

    private void RemoveScript(GameObject obj, System.Type oldComponentType)
    {
        Component c = obj.GetComponent(oldComponentType);
        if (c != null)
        {
            DestroyImmediate(c, true);
        }
    }

    private static System.Type FindTypeByName(string typeName)
    {
        foreach (System.Reflection.Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies())
        {
            System.Type type = assembly.GetType(typeName);
            if (type != null)
            {
                return type;
            }
        }
        return null;
    }
}
#endif
