using System;
using System.IO;

namespace Orciid.Media
{
	public delegate int CacheFileScorer(DateTime created, DateTime lastread, int readcount, long size);

	public abstract class MediaCache
	{
		public abstract Stream ReadFile(string filename, DateTime maxage);
		
		public abstract Stream WriteFile(string filename);
		
		public abstract void CleanUp(CacheFileScorer scorer, long maxcachesize);
		
		public void CleanUp(long maxcachesize)
		{
			CleanUp(new CacheFileScorer(DefaultCacheFileScorer), maxcachesize);
		}

		public static int DefaultCacheFileScorer(
			DateTime created, DateTime lastread, int readcount, long size)
		{
			// newer, bigger, recently and frequently requested files get higher score
			TimeSpan age = DateTime.Now - created;
			int cs = -age.Days;
			TimeSpan unused = DateTime.Now - lastread;
			int lrs = -unused.Days;
			int rcs = readcount;
			int ss = size > 0 ? (int)Math.Log10(size) : 0;
			return cs + lrs + rcs + ss;
		}
	}
	
	public class NullMediaCache: MediaCache
	{
		public override Stream ReadFile(string filename, DateTime maxage)
		{
			return null;
		}

		public override Stream WriteFile(string filename)
		{
			return Stream.Null;
		}

		public override void CleanUp(CacheFileScorer scorer, long maxcachesize)
		{
		}
	}
}
