using System.Collections;
using System.Drawing;

namespace Icarus.Graphics.Animation
{
	public class FramesetManager
	{
		/**
		 * Singleton Implementation.
		 */
		private static FramesetManager mg_Instance = new FramesetManager();

		/**
		 * Maps strings to frameset references.
		 */
		private IDictionary m_Framesets; //TODO: Maybe use soft references here, to provide caching.

		/**
		 * The default frameset provider to use.
		 */
		private IFramesetProvider m_DefaultFramesetProvider;

		/**
		 * Singleton Implementation.
		 */
		private FramesetManager()
		{
			m_Framesets = new Hashtable();
			m_DefaultFramesetProvider = new PazeraFramesetProvider();
		}

		/**
		 * Singleton Implementation.
		 */
		public static FramesetManager getInstance() { return mg_Instance; }

		/**
		 * Sets up the new default frameset provider.
		 */
		public void setDefaultFramesetProvider(IFramesetProvider provider) { m_DefaultFramesetProvider = provider; }

		/**
		 * Returns the frameset with the specified ID. If the frameset cannot be loaded, will probably throw an exception.
		 */
		public Frameset getFrameset(string id)
		{
			if (!m_Framesets.Contains(id))
			{
				this.loadFramesetFromId(id, null);
			}

			return (Frameset)m_Framesets[id];
		}

		/**
		 * Adds the frameset with the specified id. If a frameset with that id already exists, it is overwritten.
		 */
		public void addFrameset(string id, Frameset frameset)
		{
			m_Framesets.Add(id, frameset);
		}

		/**
		 * Uses the id passed in as the filename to look for the image in the base image folder.
		 */
		public void loadFramesetFromId(string id, IFramesetProvider provider)
		{
			this.loadFramesetFromFile(Icarus.Resources.ResourceManager.Instance.ImagePath + id, id, provider);
		}

		/**
		 * Loads the frameset with the specified id from the full path passed in using the specified frameset provider.
		 */
		public void loadFramesetFromFile(string filename, string id, IFramesetProvider provider)
		{
			if (provider == null)
			{
				provider = m_DefaultFramesetProvider;
			}

			Frameset new_set = new Frameset();
			provider.fillFrameset(new_set, (Bitmap)Bitmap.FromFile(filename));

			this.addFrameset(id, new_set);
		}

		/**
		 * Given an id of an image, loads it.
		 */
		public Bitmap loadImageFromId(string id)
		{
			return (Bitmap)Bitmap.FromFile(Icarus.Resources.ResourceManager.Instance.ImagePath + id);
		}
	}
}
