/* Copyright © 2014 Apex Software. All rights reserved. */
namespace Apex.AI.Editor
{
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    using Apex.Editor;
    using UnityEditor;
    using UnityEngine;

    public static class AINameMapGenerator
    {
        private static readonly Regex _nameCorrector = new Regex(@"\W+", RegexOptions.Compiled | RegexOptions.CultureInvariant);

        public static void WriteNameMapFile()
        {
            var targetFolder = AIGeneralSettings.instance.nameMapPath;
            if (string.IsNullOrEmpty(targetFolder))
            {
                targetFolder = AssetPath.GetApexRoot(true);
                AIGeneralSettings.instance.nameMapPath = targetFolder;
                AIGeneralSettings.instance.SaveChanges();
            }

            targetFolder = AssetPath.GetFullPath(targetFolder);
            if (!Directory.Exists(targetFolder))
            {
                Debug.LogWarning("Unable to create name map, please setup a target folder under settings.");
                return;
            }

            var filePath = AssetPath.Combine(targetFolder, AIGeneralSettings.NameMapFileName);

            var b = new StringBuilder();
            var aiList = StoredAIs.AIs;
            var count = aiList.count;
            for (int i = 0; i < count; i++)
            {
                var name = correctName(aiList[i].name);
                if (name != null)
                {
                    b.AppendFormat(Template.ItemTemplate, name, aiList[i].aiId);
                    b.AppendLine();
                }
            }

            using (var writer = new StreamWriter(filePath))
            {
                writer.WriteLine(Template.FileTemplate, b);
            }

            AssetDatabase.Refresh();
        }

        private static string correctName(string name)
        {
            name = _nameCorrector.Replace(name, string.Empty);
            if (!EditorUtilities.IsReservedWord(name))
            {
                return name;
            }

            return null;
        }

        private class Template
        {
            public const string ItemTemplate = "\t\tpublic static readonly Guid {0} = new Guid(\"{1}\");";
            public const string FileTemplate = @"//------------------------------------------------------------------------------
// <auto-generated>
// This class was auto generated by the AI Name Map Generator
// </auto-generated>
//------------------------------------------------------------------------------
namespace Apex.AI
{{
    using System;

    public static class AINameMap
    {{
{0}
    }}
}}";
        }
    }
}
