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

namespace OKHOSTING.Core.Drawing
{
	public static class ImageExtensions
	{
		/// <summary>
		/// Combines multiple images into a single one, horizontally aligned
		/// </summary>
		public static Image CombineHorizontal(this IEnumerable<Image> images)
		{
			if (images == null)
			{
				throw new ArgumentNullException(nameof(images));
			}

			int width = images.Sum(i => i.Width);
			int height = images.Max(i => i.Height);
			Image result = new Bitmap(width, height);

			using (var g = Graphics.FromImage(result))
			{
				g.Clear(Color.Black);

				var offset = 0;

				foreach (var image in images)
				{
					g.DrawImage(image, new Rectangle(offset, 0, image.Width, image.Height));
					offset += image.Width;
				}
			}

			return result;
		}

		/// <summary>
		/// Combines multiple images into a single one, vertically aligned
		/// </summary>
		public static Image CombineVertical(this IEnumerable<Image> images)
		{
			if (images == null)
			{
				throw new ArgumentNullException(nameof(images));
			}

			int width = images.Max(i => i.Width);
			int height = images.Sum(i => i.Height);
			Image result = new Bitmap(width, height);

			using (var g = Graphics.FromImage(result))
			{
				g.Clear(Color.Black);

				var offset = 0;

				foreach (var image in images)
				{
					g.DrawImage(image, new Rectangle(0, offset, image.Width, image.Height));
					offset += image.Height;
				}
			}

			return result;
		}

		public static Image GetThumbnail(this Image image, int width, int heigth)
		{
			return image.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
		}

		public static System.IO.Stream Save(this Image image, string extension, int quality)
		{
			//lower resolution and size
			EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);

			// Jpeg image codec
			string mimeType = MimeTypes.GetMimeType(extension);
			ImageCodecInfo codec = GetEncoderInfo(mimeType);
			EncoderParameters encoderParams = new EncoderParameters(1);
			encoderParams.Param[0] = qualityParam;

			// Save the screenshot to the specified path that the user has chosen
			var stream = new System.IO.MemoryStream();
			image.Save(stream, codec, encoderParams);

			return stream;
		}

		/// <summary>
		/// Returns the correct ImageCodecInfo according to the specified mimeType
		/// </summary>
		public static ImageCodecInfo GetEncoderInfo(string mimeType)
		{
			return ImageCodecInfo.GetImageEncoders().Where(c => c.MimeType == mimeType).SingleOrDefault();
		}
	}
}