using System.IO;
using System.Linq;
using MarketData.Utils;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Drawing;

namespace MarketData.CNNProcessing
{
	public static class BitmapExtensions
	{
// This call is used to generate the training, test, and validation bitmaps..  
// I noticed a large difference in the accuracy or the model when the quality parameter is 100.
// I therefore intentionally not using EncoderParameters to specify quality but instead taking the default quality.
			public static void SaveJPG100(this Bitmap bmp, string filename)
			{         
					EncoderParameters encoderParameters = new EncoderParameters(1);
					encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
					bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
			}

			public static void SaveJPG100(this Bitmap bmp, Stream stream)
			{
					EncoderParameters encoderParameters = new EncoderParameters(1);
					encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
					bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
			}

			private static ImageCodecInfo GetEncoder(ImageFormat format)
			{
					ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

					foreach (ImageCodecInfo codec in codecs)
					{
							if (codec.FormatID == format.Guid)
							{
									return codec;
							}
					}

					return null;
			}
	}
}
