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

using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;
using CommunityServer.Galleries.Controls;
using Telligent.CommunityServer.MetadataExtractor.Exif;
using Telligent.CommunityServer.MetadataExtractor.Jpeg;
using Image = System.Web.UI.WebControls.Image;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using Script = CommunityServer.Controls.Script;

namespace CommunityServer.ControlPanel.Galleries.Options
{
	/// <summary>
	/// Summary description for PictureOptionsPage.
	/// </summary>
	public class PictureOptionsPage : BaseGalleryPage
	{

		#region Child Controls

		protected Controls.ResourceControl Resourcecontrol1;
		protected MPContent DescriptionRegion;
		protected Script GalleryAdminScript;
		protected ResourceControl Resourcecontrol2;
		protected Literal CacheMessage;
		protected Literal ImportCount;
		protected IButton SaveButton;
		protected IButton ImportButton;
		protected MPContent TaskRegion;
		protected MPContainer MPContainer;
		protected YesNoRadioButtonList ynEnableExif;
		protected TextBox WatermarkText, WatermarkMinImageY, WatermarkMinImageX;
		protected ListBox ExifTypes;
		protected DropDownList ImageWatermarkPosition, ImageWatermarkType;
		protected Literal CacheSize;
		protected LinkButton ThumbnailRebuild, SecondaryThumbnailRebuild, CleanCache, ClearCache;
		protected HtmlAnchor ThumbnailPreview, SecondaryThumbnailPreview, PictureDetailsPreview, SlideshowPreview;
		protected HtmlInputFile WatermarkData;
		protected Image imgWatermark;
		protected ParentCategoryDropDown ImportCategoryID;
        protected StatusMessage ImportStatus;

		protected ImageSettings ThumbnailSettings,SecondaryThumbnailSettings, PictureDetailsSettings, SlideshowSettings, MaxSettings;

		#endregion

	    private void Page_Load(object sender, EventArgs e)
		{
			ThumbnailPreview.Attributes.Add("onclick", "TogglePreview('" + ThumbnailSettings.ImageXClientID + "', '" + ThumbnailSettings.ImageYClientID + "', '" + ThumbnailPreview.ClientID + "');");
			SecondaryThumbnailPreview.Attributes.Add("onclick", "TogglePreview('" + SecondaryThumbnailSettings.ImageXClientID + "', '" + SecondaryThumbnailSettings.ImageYClientID + "', '" + SecondaryThumbnailPreview.ClientID + "');");
			PictureDetailsPreview.Attributes.Add("onclick", "TogglePreview('" + PictureDetailsSettings.ImageXClientID + "', '" + PictureDetailsSettings.ImageYClientID + "', '" + PictureDetailsPreview.ClientID + "');");
			SlideshowPreview.Attributes.Add("onclick", "TogglePreview('" + SlideshowSettings.ImageXClientID + "', '" + SlideshowSettings.ImageYClientID + "', '" + SlideshowPreview.ClientID + "');");
			
			WatermarkData.Attributes.Add("onchange","__doPostBack('" + WatermarkData.ClientID + "','');") ;
			ConfigurateWatermarkImage();

			if(!IsPostBack)
            {
				// Add a list of all the different EXIF properties
                ProcessMetadataDirectory(new CSExifDirectory());
                ProcessMetadataDirectory(new CSJpegDirectory());

				foreach(string s in Enum.GetNames(typeof(WatermarkPosition)))
					ImageWatermarkPosition.Items.Add(new ListItem(ResourceManager.GetString("CP_Photos_PictureOptions_WatermarkPosition_" + s) , s)) ;

				foreach(string s in Enum.GetNames(typeof(WatermarkType)))
					ImageWatermarkType.Items.Add(new ListItem(ResourceManager.GetString("CP_Photos_PictureOptions_WatermarkType_" + s), s)) ;

				ListItem li = ImageWatermarkType.Items.FindByValue(CurrentGallery.WatermarkType.ToString()) ;
				if(li != null)
					li.Selected = true;

				li = ImageWatermarkPosition.Items.FindByValue(CurrentGallery.WatermarkPosition.ToString());
				if(li != null)
					li.Selected = true;
			
				WatermarkText.Text = CurrentGallery.WatermarkText.ToString();
				WatermarkMinImageX.Text = CurrentGallery.WatermarkMinWidth.ToString();
				WatermarkMinImageY.Text = CurrentGallery.WatermarkMinHeight.ToString();

				ynEnableExif.Items.FindByValue( CurrentGallery.EnableExif.ToString() ).Selected = true;
				
                // Select all of the DisplayExifProperties items
                for (int i = 0; i < CurrentGallery.DisplayExifProperties.Length; i++)
                {
                    ListItem item = ExifTypes.Items.FindByValue(CurrentGallery.DisplayExifProperties[i]);
                    if (item != null)
                        item.Selected = true;
                }

				ThumbnailSettings.SetFormFields(CurrentGallery.GetThumbnailSettings()) ;

				SecondaryThumbnailSettings.SetFormFields(CurrentGallery.GetSecondaryThumbnailSettings()) ;
				
				PictureDetailsSettings.SetFormFields(CurrentGallery.GetPictureDetailsSettings()) ;
				
				SlideshowSettings.SetFormFields(CurrentGallery.GetSlideshowSettings()) ;

				MaxSettings.SetFormFields(CurrentGallery.GetMaxSettings());

				// Calculate the current cache size
				CalculateCacheSize();

				CalculateImportCount();

				ImportCategoryID.SectionID = CurrentGallery.SectionID;
				ImportCategoryID.DataBind();

				ThumbnailRebuild.Text = Components.ResourceManager.GetString("CP_Photos_PictureOptions_Rebuild");
				SecondaryThumbnailRebuild.Text = Components.ResourceManager.GetString("CP_Photos_PictureOptions_Rebuild");
				CleanCache.Text = Components.ResourceManager.GetString("CP_Photos_PictureOptions_CleanCache");
				CleanCache.ToolTip = Components.ResourceManager.GetString("CP_Photos_PictureOptions_CleanCache_Help");
				ClearCache.Text = Components.ResourceManager.GetString("CP_Photos_PictureOptions_ClearCache");
				ClearCache.ToolTip = Components.ResourceManager.GetString("CP_Photos_PictureOptions_ClearCache_Help");

				// If rebuilding thumbnails is disabled, hide the buttons
				if(Jobs.Instance().IsJobEnabled("RebuildThumbnailsJob") == false)
				{
					ThumbnailRebuild.Visible = false;
					SecondaryThumbnailRebuild.Visible = false;
				}



            }
			else
			{
				//check to see if our quick add has data
				if((WatermarkData != null) && (WatermarkData.PostedFile != null) && (WatermarkData.PostedFile.ContentLength > 0))
					QuickAddWatermarkData();
				else
					CacheMessage.Visible = false;

			}
		}


		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			this.SaveButton.Click += new EventHandler(SaveButton_Click);
			AddClickEvents();
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new EventHandler(this.Page_Load);

		}
		#endregion

        private void ProcessMetadataDirectory(ICSMetadataDirectory directory)
        {
            Hashtable tags = directory.GetTags();
            foreach (int key in tags.Keys)
                ExifTypes.Items.Add(new ListItem(tags[key] as string, directory.DirectoryName() + ":" + key.ToString()));
        }

        interface ICSMetadataDirectory { Hashtable GetTags(); string DirectoryName(); }
        internal class CSExifDirectory : ExifDirectory, ICSMetadataDirectory { public Hashtable GetTags() { return tagNameMap as Hashtable; } public string DirectoryName() { return typeof(ExifDirectory).FullName; } }
        internal class CSJpegDirectory : JpegDirectory, ICSMetadataDirectory { public Hashtable GetTags() { return tagNameMap as Hashtable; } public string DirectoryName() { return typeof(JpegDirectory).FullName; } }

		private void QuickAddWatermarkData()
		{
			if (!ValidateWatermarkContentType(WatermarkData.PostedFile.ContentType))
			{
				CacheMessage.Text = "<span style='color: red'>" + string.Format(Components.ResourceManager.GetString("CP_Photos_PictureOptions_WatermarkInvalidMineType"), WatermarkData.PostedFile.ContentType) + "</span>";
				CacheMessage.Visible = true;
			}
			else
			{
				GalleryConfiguration.Instance().CacheSettings.LegacyClearStorage(CurrentGallery.SectionID) ;
				GalleryConfiguration.Instance().CacheSettings.DeleteSectionFromDisk(CurrentGallery.SectionID) ;
				
				string filename = GalleryConfiguration.Instance().CacheSettings.GetLocalWatermarkFileName(CurrentGallery.SectionID);
				if(File.Exists(filename))
					File.Delete(filename);

				WatermarkData.PostedFile.SaveAs(filename);
				this.ConfigurateWatermarkImage();
				
				CacheMessage.Text = "<span style='color: green'>" + Components.ResourceManager.GetString("CP_Photos_PictureOptions_WatermarkClearWarning") + "</span>";
				CacheMessage.Visible = true;

				CalculateCacheSize();
			}

		}

		private bool ValidateWatermarkContentType(string contentType)
		{
			switch(contentType)
			{
				case "image/bmp":
				case "image/jpeg":
				case "image/pjpeg":
				case "image/gif":
				case "image/png":
                case "image/x-png":
					return true;

				default:
					return false;
			}
			
		}

		private void ConfigurateWatermarkImage()
		{
			string filename = GalleryConfiguration.Instance().CacheSettings.GetLocalWatermarkFileName(CurrentGallery.SectionID);
			if(File.Exists(filename))
			{
				imgWatermark.ImageUrl = GalleryUrls.Instance().ViewWatermark(CurrentGallery.ApplicationKey);
				imgWatermark.Height	= 100;
			}
			else
			{
				imgWatermark.ImageUrl = "../../../utility/images/1x1.gif";
				imgWatermark.Height	= 100;
				imgWatermark.Width	= 100;
			}
			imgWatermark.BorderStyle = BorderStyle.Solid;
			imgWatermark.BorderColor = Color.Black;
			imgWatermark.BorderWidth = Unit.Pixel(1);
		}



        private void SaveButton_Click(object sender, EventArgs e)
        {
            if(Page.IsValid)
            {

				CurrentGallery.EnableExif = ynEnableExif.SelectedValue;
				
            	ArrayList properties = new ArrayList();
				foreach(ListItem item in ExifTypes.Items)
					if(item.Selected)
						properties.Add(item.Value);
				CurrentGallery.DisplayExifProperties = (string[])properties.ToArray(typeof(string));

				GalleryImageSettings settings;
				
				settings = ThumbnailSettings.GetFormFields();
				CurrentGallery.ThumbnailX = settings.Width;
				CurrentGallery.ThumbnailY = settings.Height;
				CurrentGallery.ThumbnailQuality = settings.Quality;
				CurrentGallery.ThumbnailBrightness = settings.Brightness;

				settings = SecondaryThumbnailSettings.GetFormFields();
				CurrentGallery.SecondaryThumbnailX = settings.Width;
				CurrentGallery.SecondaryThumbnailY = settings.Height;
				CurrentGallery.SecondaryThumbnailQuality = settings.Quality;

				settings = PictureDetailsSettings.GetFormFields();
				CurrentGallery.PictureDetailsX = settings.Width;
				CurrentGallery.PictureDetailsY = settings.Height;
				CurrentGallery.PictureDetailsQuality = settings.Quality;

				settings = SlideshowSettings.GetFormFields();
				CurrentGallery.SlideshowX = settings.Width;
				CurrentGallery.SlideshowY = settings.Height;
				CurrentGallery.SlideshowQuality = settings.Quality;

				settings = MaxSettings.GetFormFields();
				CurrentGallery.MaxX = settings.Width;
				CurrentGallery.MaxY = settings.Height;
				CurrentGallery.Quality = settings.Quality;

				string newWatermarkText = WatermarkText.Text.Trim();
				WatermarkPosition newWatermarkPosition = (WatermarkPosition)Enum.Parse(typeof(WatermarkPosition), ImageWatermarkPosition.SelectedValue);
				WatermarkType newWatermarkType = (WatermarkType)Enum.Parse(typeof(WatermarkType), ImageWatermarkType.SelectedValue); 

				if(CurrentGallery.WatermarkText != newWatermarkText || 
					CurrentGallery.WatermarkPosition != newWatermarkPosition ||
					CurrentGallery.WatermarkType != newWatermarkType)
				{
					GalleryConfiguration.Instance().CacheSettings.LegacyClearStorage(CurrentGallery.SectionID) ;
					GalleryConfiguration.Instance().CacheSettings.DeleteSectionFromDisk(CurrentGallery.SectionID) ;
					CalculateCacheSize();
				}

				CurrentGallery.WatermarkText = newWatermarkText;
				CurrentGallery.WatermarkPosition = newWatermarkPosition;
				CurrentGallery.WatermarkType = newWatermarkType; 
				CurrentGallery.WatermarkMinWidth = int.Parse(WatermarkMinImageX.Text) ;
				CurrentGallery.WatermarkMinHeight = int.Parse(WatermarkMinImageY.Text) ;
				
            	CommunityServer.Galleries.Galleries.Update(CurrentGallery);
			}
        }
		private void CalculateCacheSize()
		{
			// Calculate the current cache size
			CacheSize.Text = GalleryConfiguration.Instance().CacheSettings.FolderSize()  + "kb";
		}
		private void CalculateImportCount()
		{
			// Count the number of images in the Stub Gallery folder
			ImportCount.Text = GetImportFiles().Count.ToString();
		}

		private ArrayList GetImportFiles()
		{
			ArrayList importFiles = new ArrayList();
			// Count the number of images in the Stub Gallery folder
			string gallerydir = CSContext.Current.MapPath( Globals.GetSiteUrls().Locations.FindLocationByName("galleries").PhysicalPath + CurrentGallery.ApplicationKey );
		    
			// Add the end directory separator if missing
			if(!gallerydir.EndsWith( Path.DirectorySeparatorChar.ToString() ))
				gallerydir += Path.DirectorySeparatorChar;
		    
            DirectoryInfo dir = new DirectoryInfo(gallerydir);

            if (dir.Exists)
            {
                FileInfo[] files = (new DirectoryInfo(gallerydir)).GetFiles("*.*");
                foreach (FileInfo file in files)
                {
                    if (GalleryConfiguration.Instance().AttachmentSettings.Extensions.ToLower().IndexOf(file.Extension.TrimStart('.').ToLower()) > -1)
                        importFiles.Add(file);
                }
            }
		    else
            {
                ImportStatus.Visible = true;
                ImportStatus.Success = false;
                ImportStatus.Text =
                    String.Format(
                        "The gallery directory ({0}) could not be found, Importing has been disabled.  Create this directory on your web server and try again.",
                        gallerydir);
            }

		    ImportButton.Visible = importFiles.Count > 0;
		    
		    return importFiles;
		}
		private void AddClickEvents()
		{
			ThumbnailRebuild.Click += new EventHandler(ThumbnailRebuild_Click);
			SecondaryThumbnailRebuild.Click += new EventHandler(SecondaryThumbnailRebuild_Click);
			CleanCache.Click += new EventHandler(CleanCache_Click);
			ClearCache.Click += new EventHandler(ClearCache_Click);
			ImportButton.Click += new EventHandler(ImportButton_Click) ;
		}
		private void ThumbnailRebuild_Click(object sender, EventArgs e)
		{
			Hashtable pictures = GalleryDataProvider.Instance().GetAllPictures(CurrentGallery.SectionID);
			Queue queue = CSCache.Get("RebuildItems") as Queue;

			// The queue doesn't exist, so create it
			if(queue == null)
			{
				queue = Queue.Synchronized(new Queue());
				CSCache.Max("RebuildItems", queue);
			}

			// Loop the pictures and create the queue items
			foreach(int key in pictures.Keys)
			{
				GalleryPost galleryPost = pictures[key] as GalleryPost;
				string filename = GalleryConfiguration.Instance().CacheSettings.GetLocalThumbnailFileName(galleryPost) ;

				// Remove the file in advance, so if anyone browses it will regenerate it then and skip it in the job
				File.Delete(filename);

				// Create the item and queue it
				RebuildItem item = new RebuildItem(CurrentGallery, galleryPost, filename,  CurrentGallery.GetThumbnailSettings());
				queue.Enqueue(item);
			}

			// Show a message that they have been queued.
			CacheMessage.Text = "<span style='color: green'>" + string.Format(Components.ResourceManager.GetString("CP_Photos_PictureOptions_RebuildQueue"), pictures.Count) + " </span>";
			CacheMessage.Visible = true;
		}

		private void SecondaryThumbnailRebuild_Click(object sender, EventArgs e)
		{
			Hashtable pictures = GalleryDataProvider.Instance().GetAllPictures(CurrentGallery.SectionID);
			Queue queue = CSCache.Get("RebuildItems") as Queue;

			// The queue doesn't exist, so create it
			if(queue == null)
			{
				queue = Queue.Synchronized(new Queue());
				CSCache.Max("RebuildItems", queue);
			}

			// Loop the pictures and create the queue items
			foreach(int key in pictures.Keys)
			{
				GalleryPost galleryPost = pictures[key] as GalleryPost;
				string filename = GalleryConfiguration.Instance().CacheSettings.GetLocalSecondaryThumbnailFileName(galleryPost) ;

				// Remove the file in advance, so if anyone browses it will regenerate it then and skip it in the job
				File.Delete(filename);

				// Create the item and queue it
				RebuildItem item = new RebuildItem(CurrentGallery, galleryPost, filename, CurrentGallery.GetSecondaryThumbnailSettings());
				queue.Enqueue(item);
			}

			// Show a message that they have been queued.
			CacheMessage.Text = "<span style='color: green'>" + string.Format(ResourceManager.GetString("CP_Photos_PictureOptions_RebuildQueue"), pictures.Count) + " </span>";
			CacheMessage.Visible = true;
		}

		private void ImportButton_Click(object sender, EventArgs e)
		{
			ArrayList pictures = GetImportFiles();
			Queue queue = CSCache.Get("GalleryImportItems") as Queue;

			// The queue doesn't exist, so create it
			if(queue == null)
			{
				queue = Queue.Synchronized(new Queue());
				CSCache.Max("GalleryImportItems", queue);
			}

			//get the category name
			String CategoryName = null;
			if(ImportCategoryID.SelectedCategoryID > 0)
			{
				try{CategoryName = PostCategories.GetCategory(ImportCategoryID.SelectedCategoryID, CurrentGallery.SectionID).Name; }
				catch{}
			}

			// Loop the pictures and create the queue items
			foreach(FileInfo file in pictures)
			{
				// Create the item and queue it
				ImportItem item = new ImportItem(CurrentGallery, CategoryName, file.FullName, CSContext.Current.User);
				queue.Enqueue(item);
			}

			// Show a message that they have been queued.
			CacheMessage.Text = "<span style='color: green'>" + string.Format(Components.ResourceManager.GetString("CP_Photos_PictureOptions_ImportQueue"), pictures.Count) + " </span>";
			CacheMessage.Visible = true;
		}
		
		private void CleanCache_Click(object sender, EventArgs e)
		{

			// Delete all of the files except those which might be thumbnails or large thumbnails
			GalleryConfiguration.Instance().CacheSettings.LegacyCleanStorage(CurrentGallery.SectionID) ;
			CalculateCacheSize();
		}

		private void ClearCache_Click(object sender, EventArgs e)
		{

			GalleryConfiguration.Instance().CacheSettings.LegacyClearStorage(CurrentGallery.SectionID) ;
			GalleryConfiguration.Instance().CacheSettings.DeleteSectionFromDisk(CurrentGallery.SectionID) ;
			CalculateCacheSize();
		}



    }
}
