using System;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;

namespace MikuMikuDance.XNA.Model
{
    /// <summary>
    /// ToonTexture管理クラス
    /// </summary>
    static class ToonTextureManager
    {
        //保持済みデフォルトトゥーンテクスチャ
        static ExternalReference<TextureContent>[] s_Toons = null;

        static bool IsInitialized { get { return s_Toons != null; } }
        
        static void Initialize()
        {
            if (!IsInitialized)
            {//staticにして、多重読み込みを回避
                //トゥーンテクスチャの読み込み処理
                s_Toons = new ExternalReference<TextureContent>[10];
                //リソースからファイルを作成して読み込むという超セコイ方法……
                if (!Directory.Exists("ext"))
                    Directory.CreateDirectory("ext");
                //toonを1～10まで保存
                Resource1.toon01.Save(Path.Combine("ext", "toon01.bmp"));
                Resource1.toon02.Save(Path.Combine("ext", "toon02.bmp"));
                Resource1.toon03.Save(Path.Combine("ext", "toon03.bmp"));
                Resource1.toon04.Save(Path.Combine("ext", "toon04.bmp"));
                Resource1.toon05.Save(Path.Combine("ext", "toon05.bmp"));
                Resource1.toon06.Save(Path.Combine("ext", "toon06.bmp"));
                Resource1.toon07.Save(Path.Combine("ext", "toon07.bmp"));
                Resource1.toon08.Save(Path.Combine("ext", "toon08.bmp"));
                Resource1.toon09.Save(Path.Combine("ext", "toon09.bmp"));
                Resource1.toon10.Save(Path.Combine("ext", "toon10.bmp"));
                //toonの外部参照保持
                for (int i = 1; i <= 10; i++)
                {
                    string toonFileName = Path.Combine("ext", "toon");
                    if (i == 10)
                        toonFileName += "10.bmp";
                    else
                        toonFileName += "0" + i.ToString().Trim() + ".bmp";
                    s_Toons[i - 1] = new ExternalReference<TextureContent>(toonFileName);
                }
            }
            
        }


        internal static void Process(EffectMaterialContent material, string[] toonTextures, string mmdPath)
        {
            Initialize();
            if (toonTextures == null)
            {
                for (int i = 1; i <= 10; i++)
                {
                    material.Textures.Add("ToonTexture" + Convert.ToString(i).Trim(), s_Toons[i - 1]);
                }
            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    string toonPath = Path.Combine(Path.GetDirectoryName(mmdPath), toonTextures[i]);
                    string ValName = "ToonTexture" + Convert.ToString(i + 1).Trim();
                    if (!File.Exists(toonPath))
                    {
                        Regex regex = new Regex(@"^toon(?<num>\d\d)\.bmp$", RegexOptions.IgnoreCase);
                        MatchCollection mc = regex.Matches(toonTextures[i]);
                        if (mc.Count == 0)
                            throw new InvalidContentException("トゥーンテクスチャ:" + toonPath + "が見つかりません");
                        if (mc.Count > 1)
                            throw new InvalidContentException("不明なトゥーンテクスチャ：" + toonTextures[i]);
                        int toonnum;
                        if(!int.TryParse(mc[0].Groups["num"].Value,out toonnum))
                            throw new InvalidContentException("不明なトゥーンテクスチャ：" + toonTextures[i]);
                        material.Textures.Add(ValName, s_Toons[toonnum - 1]);
                    }
                    else
                    {
                        material.Textures.Add(ValName, new ExternalReference<TextureContent>(toonPath));
                    }
                }
            }
        }
    }
}
