using UnityEngine;
using UnityEditor;

public class MaterialGenerator
{
    [MenuItem("Assets/Create/Materials from selected")]
    private static void CreateMaterials()
    {
        foreach (Object obj in Selection.objects)
        {
            // TODO: Make better filtering
            if (obj.GetType() != typeof(Texture2D) || obj.name.EndsWith("_metallic") || obj.name.EndsWith("_emissive"))
            {
                continue;
            }

            var selectedTex = obj as Texture2D;

            var colorPath = AssetDatabase.GetAssetPath(selectedTex);
            var basePath = colorPath.Substring(0, colorPath.LastIndexOf('/') + 1) + "mat/";
            var metalPath = colorPath.Substring(0, colorPath.LastIndexOf('.')) + "_metallic.png";
            var emissionPath = colorPath.Substring(0, colorPath.LastIndexOf('.')) + "_emissive.png";

            var material = new Material(Shader.Find("Standard"));
            material.mainTexture = selectedTex;
            material.SetTexture("_MetallicGlossMap", EditorGUIUtility.FindTexture(metalPath));
            material.SetTexture("_EmissionMap", EditorGUIUtility.FindTexture(emissionPath));

            var newAssetName = basePath + selectedTex.name + ".mat";
            AssetDatabase.CreateAsset(material, newAssetName);
        }
        AssetDatabase.SaveAssets();
    }
}
