// Personal Webpage Engine
// Copyright(c) 2008, 2009 Mihail Kochanov
// You can contact me at StilgarAD@yahoo.com
// Copyright(c) 2009 Ivelina Georgieva
// You can contact me at ivelina.georgieva@gmail.com
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
//
// Personal Web Page Engine
//
//------------------------------------------------------------------------------


using System;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Data.Linq;

public partial class RSS : System.Web.UI.Page
{
    private BlogNETDataContext dc;
    public BlogNETDataContext DataContext
    {
        get { return dc; }
    }

    #region PageEvents

    protected void Page_PreInit(object sender, EventArgs e)
    {
        dc = new BlogNETDataContext(ConfigurationManager.ConnectionStrings["BlogNETDB"].ConnectionString);
        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<NewsItem>(ni => ni.Tags);
        dc.LoadOptions = dlo;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //get the protocol prefix, the host and eventual port from the url.
        //"www." sux! If we leave it we risk duplicate feeds because the GUID and the item URL will differ.
        string authority = Request.Url.Authority.StartsWith("www.") ? Request.Url.Authority.Substring(4) : Request.Url.Authority;
        string host = Request.Url.Scheme + Uri.SchemeDelimiter + authority;
        string articleUrl = host + ResolveUrl("~/ViewNewsItem.aspx") + "?" + Constants.QueryString.NewsItemID + "=";

        string tagParam = Request.QueryString[Constants.QueryString.Tag];

        IQueryable<NewsItem> query = SharedQueries.GetNewsItemsByTags(tagParam, dc);

        query = query.Take(15);

        //build XML out of the database query
        var xmlQuery = from ni in query
                       select new XElement("item",
                         new XElement("title", Server.HtmlDecode(ni.Title)), //this is not HTML so no HTML encoding is needed
                         new XElement("description", ni.ShortText), //this part seems to be HTML so it has better stay encoded
                         new XElement("link", articleUrl + ni.NewsItemID),
                         new XElement("guid", articleUrl + ni.NewsItemID),
                         new XElement("comments", articleUrl + ni.NewsItemID),
                         new XElement("pubDate", ni.PostDate.ToUniversalTime().ToString("R")));


        //get the last time the content has changed
        DateTime lastBuildDate = (from ni in dc.NewsItems
                                  orderby ni.PostDate descending
                                  select ni).Take(15).Max(ni => ni.LastEditedDate == null || ni.PostDate > ni.LastEditedDate ?
                                      ni.PostDate : (DateTime)ni.LastEditedDate);

        XDocument document = new XDocument(
            new XDeclaration("1.0", "utf-8", null),
            new XElement("rss",
                new XElement("channel",
                    new XElement("title", "The No-Blog Articles"),
                    new XElement("link", host),
                    new XElement("description", "This is not a blog. This is a no-blog."),
                    new XElement("lastBuildDate", lastBuildDate.ToUniversalTime().ToString("R")),
                    xmlQuery),//end of channel element
                    new XAttribute("version", "2.0"))//end of rss element
                );

        Response.ContentType = "application/rss+xml";
        document.Save(Response.Output);
        //Response.End(); this would break OutputCache
    }

    protected void Page_Unload(object sender, EventArgs e)
    {
        if (dc != null)
        {
            dc.Dispose();
        }
    }

    #endregion
}
