using System;
using System.Collections;
using CommunityServer.Components;
//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------


namespace CommunityServer.Reader.Components
{
	/// <summary>
	/// Summary description for Pictures.
	/// </summary>
	public class Feeds
	{


		private Feeds() {}


		public static ArrayList GetAllFeeds(int minutes)
		{
			return FeedReaderDataProvider.Instance().GetAllFeeds(minutes);
		}


		public static Feed GetFeed(int feedId)
		{
			return FeedReaderDataProvider.Instance().GetFeed(feedId);
		}


		public static void UpdateFeed(Feed feed)
		{
			FeedReaderDataProvider.Instance().UpdateFeed(feed.FeedId, feed.Url, feed.Title, feed.Link, feed.Language,
				feed.Generator, feed.SubscribeDate, feed.LastUpdateDate, feed.LastModified, feed.ETag, (int) feed.FeedState);
		}


		public static ArrayList GetAggregatedFeeds()
		{
			return FeedReaderDataProvider.Instance().GetRollerFeeds(Users.GetAnonymousUser().UserID);
		}


		public static void DeleteFeed(int userId, int feedId)
		{
		    EventLogs.Info("Feed " + feedId.ToString() + " was deleted by " + userId.ToString(), "FeedReader",742,CSContext.Current.SettingsID);
			FeedReaderDataProvider.Instance().DeleteFeed(userId, feedId);
		}


		public static ArrayList GetUnaggregatedFeeds(int userId)
		{
			return FeedReaderDataProvider.Instance().GetUnaggregatedFeeds(userId);
		}


		public static void AddAggregatedFeed(int userId, int feedId)
		{
			FeedReaderDataProvider.Instance().AddAggregatedFeed(userId, feedId);
		}

		public static void UserAccessCheck()
		{
			if (!ValidateUserAccess())
				throw new CSException(CSExceptionType.InvalidLicense, "You have exceeded the maximum number of users allowed by your current license.");
		}

		public static bool ValidateUserAccess()
		{
			if (Telligent.Registration.CommunityServer.FeedReaderLimit == int.MaxValue)
				return true;
			else
			{
				ArrayList users = GetUsers();	
				return users.Count < Telligent.Registration.CommunityServer.FeedReaderLimit || CheckUserInList(CSContext.Current.User, users);
			}
		}

		public static ArrayList GetUsers()
		{
			ArrayList users = (ArrayList) CSCache.Get("FeedUsers");
			if (users == null)
			{
				users = FeedReaderDataProvider.Instance().GetUsers();
				CSCache.Insert("FeedUsers", users, CSCache.HourFactor);
			}

			return users;
		}

		private static bool CheckUserInList(User user, ArrayList users)
		{
			foreach (User u in users)
			{
				if (u.UserID == user.UserID)
					return true;
			}

			return false;
		}

	}
}
