#region copyright version

/*******************************************************
 * 
 *         信游科技网络有限公司
 * 
 *     Copyright (c) 信游科技 保留所有权利。
 *     网页游戏运营管理平台 Version3
 *     2013/4/13 18:08:51 
 *     .Net : 4.0.30319.296
 * 
 *******************************************************/

#endregion

using NVelocity.App;
using NVelocity.Context;
using Commons.Collections;
using NVelocity.Runtime;
using System.Web;
using NVelocity;
using System.IO;

namespace web.Code
{
    /// <summary>
    /// 模板渲染
    /// </summary>
    internal class TemplateRender
    {
        private VelocityEngine velocity = null;
        private IContext context = null;
        /// <summary>
        /// 实例化新渲染引擎
        /// </summary>
        /// <param name="rootpath"></param>
        internal TemplateRender(string rootpath)
        {
            var file_path = HttpContext.Current.Server.MapPath(rootpath);
            velocity = new VelocityEngine();
            var props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, file_path);
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            velocity.Init(props);
        }
        /// <summary>
        /// 添加变量
        /// </summary>
        /// <param name="_key"></param>
        /// <param name="_value"></param>
        internal void Put(string _key, object _value)
        {
            if (context == null) { context = new VelocityContext(); }
            context.Put(_key, _value);
        }
        /// <summary>
        /// 显示页面
        /// </summary>
        /// <param name="template"></param>
        internal void Show(string template)
        {
            if (context == null) { context = new VelocityContext(); }
            var response = HttpContext.Current.Response;

            context.Put("jq", "jQuery");
            try
            {
                var vltTemplate = velocity.GetTemplate(template);
                var vltWriter = new StringWriter();
                vltTemplate.Encoding = "utf-8";
                vltTemplate.Merge(context, vltWriter);
                vltWriter.Close();
                response.Clear();
                var html = vltWriter.GetStringBuilder().ToString();
                response.Write(html);
                response.End();
            }
            catch (NVelocity.Exception.ParseErrorException er)
            {
                throw new System.Exception(er.Message);
            }
            catch (NVelocity.Exception.ResourceNotFoundException er)
            {
                throw new System.IO.FileNotFoundException(er.Message.Replace(".svt", ".html"));
            }
            catch (NVelocity.Exception.VelocityException er)
            {
                throw new System.Exception(er.Message);
            }

        }
    }
}
