using System;
using System.Web;

namespace ynhtm.API
{
    using Common;
    using DBUtility;

    public class Sitemap : BaseHandler
    {
        enum ChangeFreq
        {
            always,
            hourly,
            daily,
            weekly,
            mothly,
            yearly,
            never
        }

        public override void Process()
        {
            var setting = new BLL.Setting();
            var settingItem = setting.Get();
            if (settingItem.MapEnabled)
            {
                var request = this.Request;
                var response = this.Response;
                response.Clear();
                response.Cache.SetCacheability(HttpCacheability.NoCache);
                response.Cache.SetNoStore();
                var xml = this.OutputXml;
                xml.WriteStartDocument();
                Action<string, DateTime?, ChangeFreq?, double?> addUrl = delegate(string loc, DateTime? lastmod, ChangeFreq? changefreq, double? priority)
                {
                    xml.WriteStartElement("url");
                    xml.WriteElementString("loc", new Uri(request.Url, loc).ToString());
                    if (lastmod != null) xml.WriteElementString("lastmod", lastmod.Value.ToString("yyy-MM-ddTHH:mm:sszzz"));
                    if (changefreq != null) xml.WriteElementString("changefreq", Enum.GetName(typeof(ChangeFreq), changefreq.Value));
                    if (priority != null) xml.WriteElementString("priority", priority.Value.ToString("0.0"));
                    xml.WriteEndElement();
                };
                xml.WriteStartElement("urlset");
                xml.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
                addUrl(settingItem.SiteUrl.IifNullOrWhiteSpace(new Uri(request.Url, "/").ToString()), null, ChangeFreq.always, null);
                foreach (var i in new BLL.Category().GetList())
                {
                    addUrl(i.Url, null, ChangeFreq.always, null);
                }
                foreach (var i in new BLL.Post().GetList(Math.Max(settingItem.MapRowCount, 1), query: DbBase.GetQuery().Equal(DAL.Post.ENABLED, true).And().NotEqual(DAL.Post.ISHIDE, true).And().NotIn(DAL.Post.CATEGORYID, new QueryText("SELECT " + DAL.Category.CATEGORYID + " FROM " + DAL.Category.SQL_TABLE + " WHERE " + DAL.Category.MAPENABLED + " = 0"))).ToList<Model.Post>(DAL.Post.FillItem))
                {
                    addUrl(i.Url, i.LastDate, ChangeFreq.daily, null);
                }
                xml.WriteEndElement();
                xml.WriteEndDocument();
                xml.Close();
                response.End();
            }
        }
    }
}