/**
* AutoReslink.cs
* @author zhangxiaojun
* @description 部分reslink的自动生成
* @created 2022-01-17T11:07:13.807Z+08:00
* @copyright
* @last-modified 2023-04-18T19:08:27.095Z+08:00
*/

using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using iHuman.UnitySz.Framework;

public class AutoReslink
{

    public static void genOne(string reslinkAssetPath, List<(string, string, System.Type)> contentList)
    {
        var reslink = AssetDatabase.LoadAssetAtPath<ResLinkAsset>(reslinkAssetPath);
        if (reslink == null)
        {
            reslink = ScriptableObject.CreateInstance<ResLinkAsset>();
        }
        reslink.assets.Clear();
        foreach (var item in contentList)
        {
            UnityEngine.Object value;
            System.Type t = item.Item3;
            if (t == null)
            {
                value = AssetDatabase.LoadMainAssetAtPath(item.Item2);
            }
            else
            {
                value = AssetDatabase.LoadAssetAtPath(item.Item2, t);
                if (value == null)
                {
                    // 支持把图片转成 sprite格式
                    if (t == typeof(UnityEngine.Sprite))
                    {
                        TextureImporter importer = AssetImporter.GetAtPath(item.Item2) as TextureImporter ;
                        importer.textureType = TextureImporterType.Sprite;
                        importer.spriteImportMode = SpriteImportMode.Single;
                        importer.maxTextureSize = 2048;
                        importer.mipmapEnabled = false;
                        importer.spritePixelsPerUnit = 100;


                        if (importer.DoesSourceTextureHaveAlpha())
                        {
                            importer.alphaIsTransparency = true;
                        }
                        else {
                            importer.alphaIsTransparency = false;
                        }
                        EditorUtility.SetDirty(importer);
                        importer.SaveAndReimport();

                        value = AssetDatabase.LoadAssetAtPath(item.Item2, t);
                        if (value == null)
                        {
                            Debug.Log("null2:"+item.Item2);
                        }
                    }
                }

            }
            reslink.assets.Add(new ResLinkAsset.Item
            {
                Key = item.Item1,
                Val = value
            });

        }

        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(reslink)))
        {

            var parent = Directory.GetParent(reslinkAssetPath);
            Directory.CreateDirectory(parent.FullName);
            AssetDatabase.CreateAsset(reslink, reslinkAssetPath);
        }

        ResLinkEditor.Save(reslink);
        EditorUtility.SetDirty(reslink);
        AssetDatabase.SaveAssets();
    }


}


