//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.IO;
using System.Xml;
using CommunityServer.Components;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// Summary description for MaxPictureSizeModule.
	/// </summary>
	public class MaxPictureSizeModule : ICSModule
	{


        public MaxPictureSizeModule() { }

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.PrePostAttachmentUpdate += new CSPostAttachmentEventHandler(csa_PrePostAttachmentUpdate);
		}

		private void csa_PrePostAttachmentUpdate(IContent content, PostAttachment attachment, CSPostEventArgs e)
		{
			GalleryPost galleryPost = content as GalleryPost;
			Gallery CurrentGallery = galleryPost.Gallery; //GalleryConfiguration.Instance();

			if(galleryPost == null || attachment == null)
				return;

			if(CurrentGallery.HasMaxX || CurrentGallery.HasMaxY)
			{
				int maxWidth = CurrentGallery.HasMaxX ? CurrentGallery.MaxX : galleryPost.Attachment.Width;
				int maxHeight = CurrentGallery.HasMaxY ? CurrentGallery.MaxY : galleryPost.Attachment.Height;
				int quality = GalleryConfiguration.Instance().Quality;
				
				// Check the filesize
				if(galleryPost.Attachment.Width > maxWidth || galleryPost.Attachment.Height > maxHeight)
				{
					GalleryImageSettings settings = new GalleryImageSettings(maxWidth, maxHeight, quality, true);
					ImageHandling.GetMaintainedRatio(galleryPost, settings);

					string filename = string.Concat(GalleryConfiguration.Instance().CacheSettings.GetLocalFileName(CurrentGallery.SectionID, Guid.NewGuid().ToString() ) ,".jpg");
					ImageHandling.ScalePicture(filename, null, attachment, settings) ;

					if(!File.Exists(filename))
						return;

                    attachment.Content.Close();
					attachment.Content = new FileStream(filename, FileMode.Open);

					galleryPost.Attachment.Width = attachment.Width;
					galleryPost.Attachment.Height = attachment.Height;
					galleryPost.Attachment.Length =  attachment.Length;
				}
			}
		}
	}
}
