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

using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Galleries.Components;

namespace CommunityServer.ControlPanel.Controls.Galleries
{
	/// <summary>
	///		Summary description for SkinOptionsControl.
	/// </summary>
	public class SkinOptionsControl : UserControl
	{

		#region Public Properties

		public Gallery Gallery
		{
			get{return gallery;}
			set{gallery = value;}
		}

		#endregion

		#region Child Controls
		
		protected DropDownList Themes;
		protected HelpIcon HelpIcon1;
		protected FormLabel FormLabel1;
		protected FormLabel Formlabel2;
		protected HtmlGenericControl PreviewImage;
		protected HtmlGenericControl PreviewText;
		protected StatusMessage Status;
		protected HtmlGenericControl SkinSelector;
		protected HtmlTable previewtable;

		#endregion

		private const string PreivewImgTag = @"<img src=""{0}/{1}.png"" height=""150"" width=""200"" alt=""{1}.png Preview Image"" style=""border:solid 1px #CCCCCC;""/>";
		private const string ThemePath = @"{0}Galleries/{1}";
		private Gallery gallery;


		private void Page_Load(object sender, EventArgs e)
		{
				
			Themes.Attributes.Add("OnChange", "UpdatePreview();") ;
			AjaxManager.Register(this,"SkinOptionsControl");
			if(GalleryConfiguration.Instance().EnableThemes)
			{
				if(!IsPostBack && Gallery != null)
					PopulateThemes();
			}
			else
			{
				SkinSelector.Visible = false;
				previewtable.Visible = false;
				Status.Success = false;
				Status.Visible = true;
				Status.ResourceName = "CP_Photos_SkinOptions_ThemesDisabed";
			}
		}

		#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);
		}
		
		/// <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 PopulateThemes()
		{
			Themes.Items.Clear();
    
			string dirPath = Context.Server.MapPath(string.Concat(SiteUrls.Instance().Locations["Themes"], "/Galleries") );
    
			DirectoryInfo dirAllThemes = new DirectoryInfo(dirPath);
			foreach(DirectoryInfo dirTheme in dirAllThemes.GetDirectories())
			{
				DirectoryInfo dirStyle = new DirectoryInfo(Path.Combine(dirTheme.FullName, "Style"));
				if(dirStyle.Exists)
				{
					Themes.Items.Add(new ListItem(dirTheme.Name, dirTheme.Name.ToLower() + "@"));
					foreach(FileInfo fi in dirStyle.GetFiles("*.css"))
					{
                        if (string.Compare(fi.Name, "print.css", true) != 0)
                        {
                            string name = Path.GetFileNameWithoutExtension(fi.FullName).ToLower();
                            if (name != "style")
                            {
                                string themeText = string.Format("{0} - {1}", dirTheme.Name, name);
                                string themeValue = string.Format("{0}@{1}.css", dirTheme.Name, name);
                                Themes.Items.Add(new ListItem(themeText, themeValue.ToLower()));
                            }
                        }
					}
                        
				}
			}

			SetSelectedTheme(Gallery);

		}

		public void SetSelectedTheme(Gallery g)
		{
			string theme = string.Format("{0}@{1}", g.Theme,g.SecondaryCSS).ToLower().Trim();

			ListItem liTheme = Themes.Items.FindByValue(theme);
			if(liTheme != null)
				liTheme.Selected = true;

			PreviewImage.InnerHtml = GeneratePreviewImageString(Themes.SelectedValue);
			PreviewText.InnerHtml = SkinDescriptionContents(Themes.SelectedValue);
		}


		public void GetFormValues(Gallery g)
		{
			if(GalleryConfiguration.Instance().EnableThemes)
			{
				string[] theme = Themes.SelectedValue.Split('@');


				g.Theme = theme[0];
            
				if(theme.Length > 1)
					g.SecondaryCSS = theme[1];
				else
					g.SecondaryCSS = null;

			}		
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string GetPreviewText(string skin)
		{
			return SkinDescriptionContents(skin);
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string GetPreviewImage(string skin)
		{
			return GeneratePreviewImageString(skin);
		}
		
		private string SkinDescriptionContents(string themeName)
		{
			string themePath = string.Format(ThemePath, SiteUrls.Instance().Locations["themes"], themeName.Split('@')[0]);
			string descFilePath = CSContext.Current.Context.Server.MapPath(string.Format("{0}/{1}.htm", themePath, themeName));
			if(!File.Exists(descFilePath))
				return "";

			StreamReader sr = File.OpenText(descFilePath);
			String s = sr.ReadToEnd();
			sr.Close() ;
			return s;

		}

		private string GeneratePreviewImageString(string themeName)
		{
			string themePath = string.Format(ThemePath, SiteUrls.Instance().Locations["themes"],  themeName.Split('@')[0]);
			return string.Format(PreivewImgTag, themePath, themeName);

		}

	}
}
