using System;
using System.IO;
using System.Web.Razor;

namespace Muban
{
    using Compiler;
    using Template;

    public static class Parser
    {
        internal static readonly ITemplateService SERVICE;
        internal static readonly ConfigurationSection CONFIG;

        static Parser()
        {
            CONFIG = ConfigurationSection.GetConfig();
            if (CONFIG != null && !string.IsNullOrWhiteSpace(CONFIG.TemplateServiceType))
                SERVICE = (ITemplateService)Activator.CreateInstance(null, Type.GetType(CONFIG.TemplateServiceType));
            else
                SERVICE = new TemplateService();
        }

        public static string Parse(string path, Type templateType, RazorCodeLanguage language = null, Action<object> activator = null)
        {
            if (language == null) language = RazorCodeLanguage.GetLanguageByExtension(Path.GetExtension(path));
            var template = SERVICE.GetTemplate(path, templateType, language, activator);
            template.Clear();
            template.Execute();
            return template.ToString();
        }

        public static string Parse<T>(string path, RazorCodeLanguage language = null, Action<T> activator = null) where T : IFileTemplate
        {
            return Parse(path, typeof(T), language, delegate(object template)
            {
                if (activator != null) activator((T)template);
            });
        }

        public static string Eval(string code, Type templateType, RazorCodeLanguage language, Action<object> activator = null)
        {
            var template = SERVICE.Eval(code, templateType, language, activator);
            template.Execute();
            return template.ToString();
        }

        public static string Eval<T>(string code, RazorCodeLanguage language, Action<T> activator = null) where T : ITemplate
        {
            return Eval(code, typeof(T), language, delegate(object template)
            {
                if (activator != null) activator((T)template);
            });
        }
    }
}
