using System;
using System.Collections.Generic;

namespace StockPortfolio_Web
{
	/// <summary>
	/// Dictionary with entries that expire after a certain time.
	/// Use to avoid querying the web service more often than necessary.
	/// </summary>
	/// <typeparam name="T">Type of object stored in the cache.</typeparam>
	public class TimedCache<T> : Dictionary<string, TimeCachedObject<T>>
			where T : class
	{
		// ** fields
		TimeSpan _expiration = TimeSpan.MaxValue;

		// ** ctors
		public TimedCache(TimeSpan expiration)
		{
			_expiration = expiration;
		}
		public TimedCache() : this(TimeSpan.MaxValue) { }

		// ** object model
		new public T this[string key]
		{
			get
			{
				T obj;
				return TryGetValue(key, out obj)
						? obj
						: null;
			}
			set
			{
				if (value != null)
				{
					base[key] = new TimeCachedObject<T>(value);
				}
				else
				{
					base.Remove(key);
				}
			}
		}
		public bool TryGetValue(string key, out T value)
		{
			TimeCachedObject<T> to;
			if (base.TryGetValue(key, out to) &&
				  DateTime.Now.Subtract(to.Stored) <= _expiration)
			{
				value = to.Object;
				return true;
			}
			else
			{
				value = null;
				return false;
			}
		}
		public TimeSpan Expiration
		{
			get { return _expiration; }
			set { _expiration = value; }
		}
	}
	/// <summary>
	/// Class that holds an object and the time it was added to the cache
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class TimeCachedObject<T>
	{
		DateTime _stored;
		T _object;
		public TimeCachedObject(T obj)
		{
			_stored = DateTime.Now;
			_object = obj;
		}
		public T Object
		{
			get { return _object; }
		}
		public DateTime Stored
		{
			get { return _stored; }
		}
	}
}