
using System;
using System.Collections.Generic;
using System.Drawing;

using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

namespace PlanetExpress.Tools {
	
	public class TexDestroyEventArgs : EventArgs {
		public TexDestroyEventArgs(int id, string name) {
			ID =id;	
			Name = name;
		}
		public int ID;
		public string Name;
	}
	
	public static class TexMan {

		private static object SyncObj = new object();
		private static Dictionary<string, WeakReference> 
			TexNamesList = new Dictionary<string, WeakReference>();
		private static Dictionary<int, WeakReference> 
			TexIDList = new Dictionary<int, WeakReference>();
		
		public static TexClass LoadTexture(Bitmap img) {
			TexClass t = GetTexture(String.Format("{0}:{1}",
			                                      img.GetType().ToString(),
			                                      img.GetHashCode())
			                        );
			t.Load(img);
			return t;
		}
		
		public static TexClass LoadTexture(string filename) {
			WeakReference w =null;
			if (TexNamesList.TryGetValue(filename, out w)) {
				TexClass c = (TexClass)(w.Target);
				if (c != null) return c;
				TexNamesList.Remove(filename);
			}
			TexClass t = GetTexture(filename);
			t.Load(filename);
			return t;
		}
		
		public static TexClass GetTexture(string name) {
			lock (SyncObj) {
				WeakReference w =null;
				if (TexNamesList.TryGetValue(name, out w)) {
					return 
						(TexClass)(w.Target);
				}				     
				int ID = GL.GenTexture();
				TexClass t = new TexClass(ID, name);
				t.Release += ReleaseTexture;
				TexNamesList.Add(name, new WeakReference(t));
				TexIDList.Add(ID, new WeakReference(t));
				return t;
			}
		}
		
		private static void ReleaseTexture(object sender, TexDestroyEventArgs e) {
			lock (SyncObj) {				
				try {
					GL.DeleteTexture(e.ID);	
					TexIDList.Remove(e.ID);				
					TexNamesList.Remove(e.Name);
				} catch {}
			}
		}
		
		
	}
}
