using System;
using System.IO;
using System.Collections;

namespace Orciid.Media
{
	public class MimeType
	{
		// store mime type mappings as a Hashtable of ArrayList elements
		// with keys as extensions as array elements as mapped mimetypes
		private static Hashtable extensions = new Hashtable();

		private MimeType()
		{
		}

		static MimeType()
		{
			MediaConverter.RegisterConverters();
		}

		public static string GetFromExtension(string extension)
		{
			if (extension == null)
				return null;
			string ext = (extension.LastIndexOf('.') > 0 ?
				Path.GetExtension(extension) : 
				extension);
			if (ext.StartsWith("."))
				ext = ext.Substring(1);
			if (extensions.ContainsKey(ext))
				return ((ArrayList)extensions[ext])[0] as string;
			else
				return "application/octet-stream";
		}

		public static string GetExtension(string mimetype)
		{
			// remove any additional info after a semicolon
			// to handle e.g. "image/jpeg;charset=ISO-8859-1"
			int semicolon = mimetype.IndexOf(";");
			if (semicolon >= 0)
				mimetype = mimetype.Substring(0, semicolon);
			foreach (string extension in extensions.Keys)
				if (((ArrayList)extensions[extension]).Contains(mimetype))
					return extension;
			return "dat";
		}
		
		public static void RegisterExtension(string extension, string mimetype)
		{
			if (extensions.ContainsKey(extension))
			{
				ArrayList a = (ArrayList)extensions[extension];
				if (!a.Contains(mimetype))
					a.Add(mimetype);
			}
			else
			{
				ArrayList a = new ArrayList();
				a.Add(mimetype);
				extensions[extension] = a;
			}
		}
	}
}
