using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace CaLib.User
{
	public abstract class ImageUtil
	{
		public static Image CreateThumbnail(Image image, int w, int h, int spacing)
		{
			float fw = (float)w / (float)image.Width;
			float fh = (float)h / (float)image.Height;

			float scale = Math.Min(fw, fh);
			int nw = (int)(image.Width * scale);
			int nh = (int)(image.Height * scale);

			return new Bitmap(image, nw, nh);
		}

		static readonly ImageFormat[] imageFormat_ = new ImageFormat[]
		{
			ImageFormat.Bmp, ImageFormat.Gif, ImageFormat.Jpeg, ImageFormat.Png
		};

		class ImageFormatCodecInfo
		{
			public ImageFormat format_;
			public ImageCodecInfo info_;

			public ImageFormatCodecInfo(ImageFormat format, ImageCodecInfo info)
			{
				format_ = format;
				info_ = info;
			}
		}

		static readonly ImageFormatCodecInfo[] imageFormatInfo_;

		static ImageUtil()
		{
			ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

			List<ImageFormatCodecInfo> list = new List<ImageFormatCodecInfo>();
			foreach (ImageCodecInfo ici in encoders)
			{
				ImageFormat imf = FindImageFormat(ici);
				if (imf == null)
				{
					continue;
				}

				list.Add(new ImageFormatCodecInfo(imf, ici));
			}
			imageFormatInfo_ = list.ToArray();
		}

		static ImageFormat FindImageFormat(ImageCodecInfo codec)
		{
			foreach (ImageFormat ici in imageFormat_)
			{
				if (codec.FormatID.Equals(ici.Guid))
				{
					return ici;
				}
			}
			return null;
		}

		const int USE_INDEX = 0;

		public static ImageFormat FindImageFormat(string ext)
		{
			foreach (ImageFormatCodecInfo ici in imageFormatInfo_)
			{
				string[] exts = ici.info_.FilenameExtension.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

				string tmp = exts[USE_INDEX].Replace("*.", "");

				if (tmp.Equals(ext, StringComparison.CurrentCultureIgnoreCase) == true)
				{
					return ici.format_;
				}
			}
			return ImageFormat.Bmp;
		}

		public static string GetFilter()
		{
			StringBuilder sb = new StringBuilder();

			foreach (ImageFormatCodecInfo ici in imageFormatInfo_)
			{
				string[] exts = ici.info_.FilenameExtension.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

				sb.AppendFormat(@"{0}({1})|{2}|", ici.info_.FormatDescription, exts[USE_INDEX], exts[USE_INDEX]);
			}

			string ret = sb.ToString();
			return ret.Remove(ret.Length - 1);
		}

	}
}
