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

namespace Onward.CustomContent.EditorTools
{
    public static class FixLitMaterials
    {
        [UnityEditor.MenuItem("ONWARD/Fix Lit materials in scene")]
        static void Fix()
        {
            const string SrcProperty = "Base_Map";
            const string DstProperty = "_BaseMap";

            var allMats = FindAllMaterials();

            foreach (var m in allMats)
            {
                Texture t = m.GetTexture(SrcProperty);

                if (t == null)
                {
                    continue;
                }

                Debug.Log($"Migrating {m.name} from {SrcProperty} to {DstProperty}");

                m.SetTexture(DstProperty, t);

                UnityEditor.EditorUtility.SetDirty(m);
            }
        }

        static HashSet<Material> FindAllMaterials()
        {
            HashSet<Material> materials = new HashSet<Material>();

            foreach (var go in UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects())
            {
                foreach (var r in go.GetComponentsInChildren<Renderer>(true))
                {
                    if (r == null)
                    {
                        continue;
                    }

                    foreach (var m in r.sharedMaterials)
                    {
                        if (m == null)
                        {
                            continue;
                        }

                        materials.Add(m);
                    }
                }
            }

            return materials;
        }
    }
}
#endif