// 说环节配置文件生成器

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Office.CustomUI;
using iHuman.UnitySz.Framework;
using UnityEditor;
using UnityEngine;

public class ReslinkGen
{
    const string artPathRoot = "Assets/art/game/gushi/say/";
    const string codePathRoot = "Assets/gamesrc/poetry/say";
    // [MenuItem("Assets/自定义创建/古诗/say/生成img&sound的reslink")]
    public static void genSayResLink() {
        String[] artSubDirs = Directory.GetDirectories(artPathRoot);
        String[] artGameIdPaths = artSubDirs.Where(dir => Regex.IsMatch(dir, @"\d+$")).ToArray();
        foreach (String gameIdPath in artGameIdPaths) {
            String gameId = Path.GetFileName(gameIdPath);
            String codeGameIdDir = Path.Combine(codePathRoot,gameId);
            String resLinkName = "rootreslink.asset";
            String resLinkPath = Path.Combine(codeGameIdDir,resLinkName);
            if (!Directory.Exists(codeGameIdDir)) {Directory.CreateDirectory(codeGameIdDir);}
            if (File.Exists(resLinkPath)) File.Delete(resLinkPath);
            ResLinkAsset resLinkAsset = ScriptableObject.CreateInstance<ResLinkAsset>();
            string bgPath = Path.Combine(gameIdPath,"image/bg");
            string soundPath = Path.Combine(gameIdPath,"sound/poetries");
            addToResLink(resLinkAsset,bgPath,"*.png","BG");
            addToResLink(resLinkAsset,soundPath,"*.ogg","");
            AssetDatabase.CreateAsset(resLinkAsset,resLinkPath);
            ResLinkEditor.Save(resLinkAsset);
        }
    }

    private static void addToResLink(ResLinkAsset resLinkAsset,string dirPath,string pattern,string resName) {
        if (Directory.Exists(dirPath)) {
            string[] paths = Directory.GetFiles(dirPath, pattern);
            foreach (string path in paths) {
                var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
                if (obj is Texture2D) {
                    obj = AssetDatabase.LoadAssetAtPath<Sprite>(path);
                }
                string assetKey = Path.GetFileNameWithoutExtension(path);
                if (resName !=  "") {
                    assetKey = resName + "_" + assetKey;
                }
                var item = new ResLinkAsset.Item{Key = assetKey,Val = obj};
                resLinkAsset.assets.Add(item);
            }

        }
    }
}