using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls; 
using Meta.Web;
using Meta.Web.Controls.Template;  

namespace MetaSite.Components.Controls.Views
{
	/// <summary>
	/// ImageAdmin。
	/// </summary>
	public class ImageAdmin : BaseTemplateControl
	{
		private string NoFileMessage = "您没有选择文件。";
		private string UploadSuccessMessage = "上传成功";
		private string UploadFailureMessage = "上传失败。";
		private string NoImagesMessage = "该文件夹不存在或者是空的";
		private string NoFolderSpecifiedMessage = "您要上传到的文件夹不存在。";
		private string NoFileToDeleteMessage = "您没有选中要删除的文件。";
		private string InvalidFileTypeMessage = "您无法上传这种类型的文件。";
		private string[] AcceptedFileTypes = new string[] {"jpg","jpeg","jpe","gif","png","swf"};

		// Configuration		
		private bool	DeleteIsEnabled = true;         // 是否允许删除文件
		private string	DefaultImageFolder = Meta.Web.Configuration.Settings.Theme +"\\Images";  // 默认的起始文件夹


		Button UploadImage;
		Button DeleteImage;

		HtmlInputFile UploadFile;		
		HtmlInputHidden  CurrentImagesFolder;
		HtmlInputHidden  FileToDelete;

		RegularExpressionValidator FileValidator;	

		Panel GalleryPanel;		
		Label gallerymessage;
		Literal ResultsMessage;

		public string DefaultUrl 
		{
			get
			{
				object o = ViewState["DefaultUrl"]; 
				return o == null? string.Empty : (string)o;
			} 			
			set { ViewState["DefaultUrl"] = value; }
		}		

		public string RootImagesFolder
		{
			get
			{
				object o = ViewState["RootImagesFolder"];
				return o==null? DefaultImageFolder : (string)o;
			}
			set	{ViewState["RootImagesFolder"] = value;	}
		}


		protected override void AttachChildControls()
		{
			UploadImage = (Button)FindControl( "UploadImage" );
			UploadImage.Click += new EventHandler(UploadImage_OnClick);

			DeleteImage = (Button)FindControl( "DeleteImage" );
			DeleteImage.Click += new EventHandler(DeleteImage_OnClick); 

			FileValidator = (RegularExpressionValidator)FindControl( "FileValidator" );
			UploadFile = (HtmlInputFile)FindControl( "UploadFile" );
			
			CurrentImagesFolder = (HtmlInputHidden )FindControl( "CurrentImagesFolder" );
			FileToDelete = (HtmlInputHidden )FindControl( "FileToDelete" );

			GalleryPanel = (Panel)FindControl( "GalleryPanel" );			
			gallerymessage = (Label)FindControl( "gallerymessage" );
			ResultsMessage = (Literal)FindControl( "ResultsMessage" );

			Context.Items.Add(PageHead.key,"图片资源");

			if ( !AdminSettings.InAdminRoles("ManageImages"))
			{
				ForumPermission.RedirectOrExcpetion();			
			}

			Page_Load();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);
			//Page_Load();
		}


		private void Page_Load() 
		{
			//string isframe = "" + Page.Request["frame"];
	
			//if (isframe != "") 
			//{
				//MainPage.Visible = true;
				//iframePanel.Visible = false;
	
				string rif = "" + Page.Request["rif"];
				string cif = "" + Page.Request["cif"];	

				if (cif != "") 
				{					
					CurrentImagesFolder.Value = cif;
				} 
				else 
				{					
					CurrentImagesFolder.Value = DefaultImageFolder;	
				}

				//UploadPanel.Visible = UploadIsEnabled;
				DeleteImage.Visible = DeleteIsEnabled;

				string FileErrorMessage = "";
				string ValidationString = ".*(";
				//[\.jpg]|[\.jpeg]|[\.jpe]|[\.gif]|[\.png])$"
				for (int i=0;i<AcceptedFileTypes.Length; i++) 
				{
					ValidationString += "[\\." + AcceptedFileTypes[i] + "]";
					if (i < (AcceptedFileTypes.Length-1)) ValidationString += "|";
					FileErrorMessage += AcceptedFileTypes[i];
					if (i < (AcceptedFileTypes.Length-1)) FileErrorMessage += ", ";
				}
				FileValidator.ValidationExpression = ValidationString+")$";
				FileValidator.ErrorMessage=FileErrorMessage;

				if (!Page.IsPostBack) 
				{
					DisplayImages();
				}
		//	} 
			//else 
			//{
		
			//}
		}

		public void UploadImage_OnClick(object sender, EventArgs e) 
		{	
			if (Page.IsValid) 
			{
				if (CurrentImagesFolder.Value != "") 
				{
					if (UploadFile.PostedFile.FileName.Trim() != "") 
					{
						if (IsValidFileType(UploadFile.PostedFile.FileName)) 
						{
							try 
							{
								string UploadFileName = "";
								string UploadFileDestination = "";
								UploadFileName = UploadFile.PostedFile.FileName;
								UploadFileName = UploadFileName.Substring(UploadFileName.LastIndexOf("\\")+1);
								UploadFileDestination = HttpContext.Current.Request.PhysicalApplicationPath;
								UploadFileDestination += CurrentImagesFolder.Value;
								UploadFileDestination += "\\";
								UploadFile.PostedFile.SaveAs(UploadFileDestination + UploadFileName);
								ResultsMessage.Text = UploadSuccessMessage;
							} 
							catch
							{
								//ResultsMessage.Text = "Your file could not be uploaded: " + ex.Message;
								ResultsMessage.Text = UploadFailureMessage;
							}
						} 
						else 
						{
							ResultsMessage.Text = InvalidFileTypeMessage;
						}
					} 
					else 
					{
						ResultsMessage.Text = NoFileMessage;
					}
				} 
				else 
				{
					ResultsMessage.Text = NoFolderSpecifiedMessage;
				}
			} 
			else 
			{
				ResultsMessage.Text = InvalidFileTypeMessage;
		
			}
			DisplayImages();
		}

		public void DeleteImage_OnClick(object sender, EventArgs e) 
		{
			if (FileToDelete.Value != "" && FileToDelete.Value != "undefined") 
			{
				try 
				{
					string AppPath = HttpContext.Current.Request.PhysicalApplicationPath;
					System.IO.File.Delete(AppPath  + CurrentImagesFolder.Value + "\\" + FileToDelete.Value);
					ResultsMessage.Text = "已删除: " + FileToDelete.Value;
				} 
				catch
				{			
					ResultsMessage.Text = "删除失败。";
				}
			} 
			else 
			{
				ResultsMessage.Text = NoFileToDeleteMessage;
			}
			DisplayImages();
		}

		private bool IsValidFileType(string FileName) 
		{
			string ext = FileName.Substring(FileName.LastIndexOf(".")+1,FileName.Length-FileName.LastIndexOf(".")-1);
			for (int i=0; i<AcceptedFileTypes.Length; i++) 
			{
				if (ext == AcceptedFileTypes[i]) 
				{
					return true;
			
				}	
			}
			return false;
		}


		private string[] ReturnFilesArray() 
		{
			if (CurrentImagesFolder.Value != "") 
			{
				try 
				{
					string AppPath = HttpContext.Current.Request.PhysicalApplicationPath;
					string ImageFolderPath = AppPath + CurrentImagesFolder.Value;
					string[] FilesArray = System.IO.Directory.GetFiles(ImageFolderPath,"*");
					return FilesArray;			
				} 
				catch 
				{
		
					return null;
				}
			} 
			else 
			{
				return null;
			}

		}

		private string[] ReturnDirectoriesArray() 
		{
			if (CurrentImagesFolder.Value != "") 
			{
				try 
				{
					string AppPath = HttpContext.Current.Request.PhysicalApplicationPath;
					string CurrentFolderPath = AppPath + CurrentImagesFolder.Value;
					string[] DirectoriesArray = System.IO.Directory.GetDirectories(CurrentFolderPath,"*");
					return DirectoriesArray ;
				} 
				catch 
				{
					return null;
				}
			} 
			else 
			{
				return null;
			}
		}

		public void DisplayImages() 
		{
			string[] FilesArray = ReturnFilesArray();
			string[] DirectoriesArray = ReturnDirectoriesArray();
			string AppPath = HttpContext.Current.Request.PhysicalApplicationPath;
			string AppUrl;
	
			//Get the application's URL
			if (Page.Request.ApplicationPath == "/")
				AppUrl = Page.Request.ApplicationPath;
			else
				AppUrl = Page.Request.ApplicationPath + "/";
	
			GalleryPanel.Controls.Clear();
			if ( (FilesArray == null || FilesArray.Length == 0) && (DirectoriesArray == null || DirectoriesArray.Length == 0) ) 
			{
				gallerymessage.Text = NoImagesMessage + ": " + RootImagesFolder;
			} 
			else 
			{
				string ImageFileName = "";
				string ImageFileLocation = "";

				int thumbWidth = 94;
				int thumbHeight = 94;
		
				if (CurrentImagesFolder.Value != RootImagesFolder) 
				{

					System.Web.UI.HtmlControls.HtmlImage myHtmlImage = new System.Web.UI.HtmlControls.HtmlImage();
					myHtmlImage.Src = AppUrl + "FreeTextBox/images/ftb/folder.up.gif";
					myHtmlImage.Attributes["unselectable"]="on"; 
					myHtmlImage.Attributes["align"]="absmiddle"; 
					myHtmlImage.Attributes["vspace"]="36"; 

					string ParentFolder = CurrentImagesFolder.Value.Substring(0,CurrentImagesFolder.Value.LastIndexOf("\\"));

					System.Web.UI.WebControls.Panel myImageHolder = new System.Web.UI.WebControls.Panel();					
					myImageHolder.CssClass = "imageholder";
					myImageHolder.Attributes["unselectable"]="on"; 
					myImageHolder.Attributes["onclick"]="divClick(this,'');";  
					myImageHolder.Attributes["ondblclick"]="gotoFolder('" + RootImagesFolder + "','" + ParentFolder.Replace("\\","\\\\") + "');";  
					myImageHolder.Controls.Add(myHtmlImage);

					System.Web.UI.WebControls.Panel myMainHolder = new System.Web.UI.WebControls.Panel();
					myMainHolder.CssClass = "imagespacer";
					myMainHolder.Controls.Add(myImageHolder);

					System.Web.UI.WebControls.Panel myTitleHolder = new System.Web.UI.WebControls.Panel();
					myTitleHolder.CssClass = "titleHolder";
					myTitleHolder.Controls.Add(new LiteralControl("向上"));
					myMainHolder.Controls.Add(myTitleHolder);

					GalleryPanel.Controls.Add(myMainHolder);		
			
				}
		
				foreach (string _Directory in DirectoriesArray) 
				{
			
					try 
					{
						string DirectoryName = _Directory.ToString();
				

						System.Web.UI.HtmlControls.HtmlImage myHtmlImage = new System.Web.UI.HtmlControls.HtmlImage();
						myHtmlImage.Src = AppUrl + "FreeTextBox/images/ftb/folder.big.gif";
						myHtmlImage.Attributes["unselectable"]="on"; 
						myHtmlImage.Attributes["align"]="absmiddle"; 
						myHtmlImage.Attributes["vspace"]="29"; 

						System.Web.UI.WebControls.Panel myImageHolder = new System.Web.UI.WebControls.Panel();					
						myImageHolder.CssClass = "imageholder";
						myImageHolder.Attributes["unselectable"]="on"; 
						myImageHolder.Attributes["onclick"]="divClick(this);";  
						myImageHolder.Attributes["ondblclick"]="gotoFolder('" + RootImagesFolder + "','" + DirectoryName.Replace(AppPath,"").Replace("\\","\\\\") + "');";  
						myImageHolder.Controls.Add(myHtmlImage);

						System.Web.UI.WebControls.Panel myMainHolder = new System.Web.UI.WebControls.Panel();
						myMainHolder.CssClass = "imagespacer";
						myMainHolder.Controls.Add(myImageHolder);

						System.Web.UI.WebControls.Panel myTitleHolder = new System.Web.UI.WebControls.Panel();
						myTitleHolder.CssClass = "titleHolder";
						myTitleHolder.Controls.Add(new LiteralControl(DirectoryName.Replace(AppPath + CurrentImagesFolder.Value + "\\","")));
						myMainHolder.Controls.Add(myTitleHolder);

						GalleryPanel.Controls.Add(myMainHolder);		
					} 
					catch 
					{
						// nothing for error
					}
				}
		
				foreach (string ImageFile in FilesArray) 
				{

					try 
					{

						ImageFileName = ImageFile.ToString();
						ImageFileName = ImageFileName.Substring(ImageFileName.LastIndexOf("\\")+1);
						ImageFileLocation = AppUrl;
						ImageFileLocation = ImageFileLocation.Substring(ImageFileLocation.LastIndexOf("\\")+1);
						//galleryfilelocation += "/";
						ImageFileLocation += CurrentImagesFolder.Value;
						ImageFileLocation += "/";
						ImageFileLocation += ImageFileName;
						System.Web.UI.HtmlControls.HtmlImage myHtmlImage = new System.Web.UI.HtmlControls.HtmlImage();						
					
						myHtmlImage.Src = ImageFileLocation;							

						System.Drawing.Image myImage = null;
						if (System.IO.Path.GetExtension( ImageFileName).ToLower() == ".swf")  
						{
							myImage = new System.Drawing.Bitmap(thumbWidth,thumbHeight);	
							myHtmlImage.Src = AppUrl + "FreeTextBox/images/ftb/"+ DefaultUrl;
						}
						else						
							myImage = System.Drawing.Image.FromFile(ImageFile.ToString());
						

						myHtmlImage.Attributes["unselectable"]="on";  
						//myHtmlImage.border=0;

						// landscape image
						if (myImage.Width > myImage.Height) 
						{
							if (myImage.Width > thumbWidth) 
							{
								myHtmlImage.Width = thumbWidth;
								myHtmlImage.Height = Convert.ToInt32(myImage.Height * thumbWidth/myImage.Width);						
							} 
							else 
							{
								myHtmlImage.Width = myImage.Width;
								myHtmlImage.Height = myImage.Height;
							}
							// portrait image
						} 
						else 
						{
							if (myImage.Height > thumbHeight) 
							{
								myHtmlImage.Height = thumbHeight;
								myHtmlImage.Width = Convert.ToInt32(myImage.Width * thumbHeight/myImage.Height);
							} 
							else 
							{
								myHtmlImage.Width = myImage.Width;
								myHtmlImage.Height = myImage.Height;
							}
						}
				
						if (myHtmlImage.Height < thumbHeight) 
						{
							myHtmlImage.Attributes["vspace"] = Convert.ToInt32((thumbHeight/2)-(myHtmlImage.Height /2)).ToString(); 
						}


						System.Web.UI.WebControls.Panel myImageHolder = new System.Web.UI.WebControls.Panel();					
						myImageHolder.CssClass = "imageholder";
						myImageHolder.Attributes["onclick"]="divClick(this,'" + ImageFileName + "');";  
						myImageHolder.Attributes["ondblclick"]="returnImage('" + ImageFileLocation.Replace("\\","/") + "','" + myImage.Width.ToString() + "','" + myImage.Height.ToString() + "');";  
						myImageHolder.Controls.Add(myHtmlImage);


						System.Web.UI.WebControls.Panel myMainHolder = new System.Web.UI.WebControls.Panel();
						myMainHolder.CssClass = "imagespacer";
						myMainHolder.Controls.Add(myImageHolder);

						System.Web.UI.WebControls.Panel myTitleHolder = new System.Web.UI.WebControls.Panel();
						myTitleHolder.CssClass = "titleHolder";
						myTitleHolder.Controls.Add(new LiteralControl(ImageFileName + "<BR>" + myImage.Width.ToString() + "x" + myImage.Height.ToString()));
						myMainHolder.Controls.Add(myTitleHolder);

						//GalleryPanel.Controls.Add(myImage);
						GalleryPanel.Controls.Add(myMainHolder);
				
						myImage.Dispose();
					} 
					catch
					{
						System.Web.UI.HtmlControls.HtmlImage myHtmlImage = new System.Web.UI.HtmlControls.HtmlImage();			
                       
					}
				}
				gallerymessage.Text = "";
			}
		}
	}
}
