//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using CommunityServer.Reader.Components;
using CommunityServer.Components;
using CommunityServer.Configuration;
using Rss;
using System.Text.RegularExpressions;
using System.Net;

namespace CommunityServer.ControlPanel.Components
{
	public class AnnouncementsFeed
	{
		static Regex stripHtml = new Regex("<[^>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

		private AnnouncementsFeed()
		{
		}

		public static RssItemCollection GetAnnouncements()
		{
			RssItemCollection items;

			items = (RssItemCollection) CSCache.Get("CP-Announcements");
			if (items != null)
				return items;

			items = new RssItemCollection();
			if (Globals.IsNullorEmpty(CSConfiguration.GetConfig().AnnouncementRssUrl))
				return items;

			Feed feed = new Feed();
			feed.Url = CSConfiguration.GetConfig().AnnouncementRssUrl;
			feed.Title = "Control Panel Announcements";

			RssFeed rssFeed = null;
			try
			{
				HttpWebRequest request = feed.CreateRequest();
				request.Timeout = 10000; // timeout in ten seconds
				rssFeed = RssFeed.Read(request);	
			}
			catch (Exception)
			{
				return items;
			}

			if (rssFeed != null && rssFeed.Channels != null && rssFeed.Channels.Count >= 1) 
			{
				RssItem newItem;
				foreach (RssItem item in rssFeed.Channels[0].Items)
				{
					newItem = new RssItem();
					newItem.Link = item.Link;
					newItem.Title = stripHtml.Replace(item.Title, "");
					newItem.Description = stripHtml.Replace(item.Description, "");
					if (newItem.Description.Length > 250)
						newItem.Description = newItem.Description.Substring(0, 250) + "...";
					
					items.Add(newItem);

					if (items.Count == 5)
						break;
				}
			}

			CSCache.Insert("CP-Announcements", items, new System.Web.Caching.CacheDependency(null, new string[] { CommunityServer.Configuration.CSConfiguration.CacheKey }), 60 * 60 * 24);

			return items;
		}
	}
}
