using System;
using System.Web;

namespace ynhtm.Theme
{
    using Common;
    using Theme.Template;

    public class Handler<Template> : BaseHandler, IHandler where Template : ITemplate
    {
        public Handler()
        {
            this.ContentType = "text/html";
        }

        public virtual string FileName { get; set; }

        public override void ProcessRequest(HttpContext context)
        {
            var response = context.Response;
            response.Clear();
            var setting = new BLL.Setting();
            var settingItem = setting.Get();
            if (!settingItem.SiteEnabled) throw new HttpException(503, "网站维护中！");
            if (settingItem.CacheEnabled)
            {
                response.Cache.SetExpires(DateTime.Now.AddMinutes(Math.Max(settingItem.CacheExpire, 1)));
                response.Cache.SetCacheability((HttpCacheability)settingItem.CacheType);
            }
            base.ProcessRequest(context);
        }

        public string ContentType { get; set; }

        public override void Process()
        {
            this.Response.ContentType = this.ContentType;
            this.Response.Write(Parser.Parse<Template>(this.FileName, activator: this.Activator));
        }

        protected virtual void Activator(Template instance)
        {
            instance.User = this.User;
            instance.Request = this.Request;
            instance.Response = this.Response;
            instance.Session = this.Session;
        }
    }

    public class Handler<Template, TModel> : Handler<Template> where Template : ITemplate<TModel>
    {
        public Handler(TModel model)
        {
            this.Model = model;
        }

        public TModel Model { get; private set; }

        protected override void Activator(Template instance)
        {
            base.Activator(instance);
            ((ITemplate<TModel>)instance).Model = this.Model;
        }
    }
}
