using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Security;
using System.Xml;

namespace baoge.Admin
{
	/// <summary>
	/// webfile 的摘要说明。
	/// </summary>
	public class webfile : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Label Header;
		protected System.Web.UI.WebControls.ImageButton UpBtn;
		protected System.Web.UI.WebControls.ImageButton GoRoot;
		protected System.Web.UI.WebControls.PlaceHolder FilesFolders;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			if(Session["AdminName"]==null)
			{
				Response.Redirect("Admin_Login.aspx");
			}
			if(Session["Path"] == null || Session["Path"].ToString() == "")
				Session["Path"] = "/baoge/";	//default is root directory
			if(Session["Path"].ToString() != "/baoge/")			
				Header.Text = "当前显示的内容位于 <b>" + Session["Path"].ToString() + "</b> 目录.";				
			else
			{
				Header.Text = "当前显示的内容位于 <B>根目录.</b>";	
				UpBtn.Visible = false;		// this button has no context in the root dir
				GoRoot.Visible = false;		// same
			}
			showFiles();	// list the files and folders in the current directory
		}



		public void showFiles()
		{					
			// safety checks handled by checkValidSessionPath function
			DirectoryInfo mainDir = checkValidSessionPath();
			if(mainDir == null)	return;	// bail out

			int alternate = 0;	// used for alternating background color in table rows

			foreach(DirectoryInfo d in mainDir.GetDirectories())
			{				
				// build up some literal controls, and buttons for the row of the table representing the directory
				Literal newColumn1 = new Literal();
				newColumn1.Text = "</td> <td>&nbsp;";	
				Literal newColumn2 = new Literal();
				newColumn2.Text = "</td> <td>&nbsp;";	
				Literal newColumn3 = new Literal();
				newColumn3.Text = "</td> <td>";	

				// display a folder icon
				Literal picColumn = new Literal();
				if(alternate%2 == 1)	// alternate back-colour of rows
					picColumn.Text = "<TR><td><img src=pics/folder.gif></td><td>";
				else
					picColumn.Text = "<TR bgcolor='#e8e8e8'><td><img src=pics/folder.gif></td><td>";
				
				// this link changes the path to the directory being clicked
				LinkButton changePathBtn = new LinkButton();
				changePathBtn.Text = d.Name.ToString();
				changePathBtn.CommandArgument = d.Name.ToString();
				changePathBtn.Command += new CommandEventHandler(ChangePath);

				// this link deletes the directory, but it must be empty for the delete to be successful
				//				HyperLink deleteBtn = new HyperLink();
				//				deleteBtn.ImageUrl = "pics/delete_icon.gif";
				//				deleteBtn.NavigateUrl = "javascript:confirmDelete('delete.aspx?Type=Folder&Name=" + Server.UrlEncode(Session["Path"].ToString() + d.Name.ToString()) + "','" + d.Name.ToString()+ "');";	// use client-side confirm function for deleting
				
				Literal endRow = new Literal();
				endRow.Text = "</td></tr>";

				// add the controls to the container in the webform
				this.FilesFolders.Controls.Add(picColumn);
				this.FilesFolders.Controls.Add(changePathBtn);
				this.FilesFolders.Controls.Add(newColumn1);
				this.FilesFolders.Controls.Add(newColumn2);
				this.FilesFolders.Controls.Add(newColumn3);
				//				this.FilesFolders.Controls.Add(deleteBtn);
				this.FilesFolders.Controls.Add(endRow);

				alternate++;	// bump the int for back-colour alternation
			}

			foreach(FileInfo f in mainDir.GetFiles())
			{	
				// build up some literal controls, and buttons for the row of the table representing the file
				Literal newColumn1 = new Literal();
				newColumn1.Text = "</td> <td>";	
				Literal newColumn2 = new Literal();
				newColumn2.Text = "</td> <td>";	
				Literal newColumn3 = new Literal();
				newColumn3.Text = "</td> <td>";	

				Literal newColumn = new Literal();
				newColumn.Text = "</td> <td>";

				// display a file icon
				Literal picColumn = new Literal();
				if(alternate%2 == 1)
					picColumn.Text = "<TR><td><img src=pics/file.gif></td><td>";
				else
					picColumn.Text = "<TR bgcolor='#e8e8e8'><td><img src=pics/file.gif></td><td>";
				
				// this link goes directly to the file (not edit mode)
				HyperLink goToBtn = new HyperLink();
				goToBtn.Text = f.Name.ToString();
				goToBtn.NavigateUrl = "http://" + Request.ServerVariables["SERVER_NAME"].ToString() + Session["Path"].ToString() + f.Name.ToString();

				Literal gap = new Literal();
				gap.Text = " &nbsp; - &nbsp; ";		

				// this link edits the file when clicked
				//				HyperLink editBtn = new HyperLink();
				//				editBtn.Text = "Edit";
				//				editBtn.ToolTip = f.Name.ToString();
				//				editBtn.NavigateUrl = "edit.aspx?File=" + Server.UrlEncode(Session["Path"].ToString() + f.Name.ToString());
		
				// work out what string to display for the file, e.g. bytes, kilobytes, or megabytes
				long fileSize = f.Length;
				string fileSizeStr;
				if(fileSize > 1000000) fileSizeStr = fileSize/1000000 + " Mb";
				else if(fileSize > 1000) fileSizeStr = fileSize/1000 + " Kb";
				else fileSizeStr = fileSize + " b";

				// size of file
				Label sizeLbl = new Label();
				sizeLbl.Text = fileSizeStr;

				// last modified datetime of file
				Label modLbl = new Label();
				modLbl.Text = f.LastWriteTime.ToString();
				
				// set up delete button
				//				HyperLink deleteBtn = new HyperLink();
				//				deleteBtn.ImageUrl = "pics/delete_icon.gif";
				//				deleteBtn.NavigateUrl = "javascript:confirmDelete('delete.aspx?Type=File&Name=" + Server.UrlEncode(Session["Path"].ToString() + f.Name.ToString()) + "','" + f.Name.ToString()+ "');";

				Literal endRow = new Literal();
				endRow.Text = "</td></tr>";

				// add controls to container
				this.FilesFolders.Controls.Add(picColumn);
				this.FilesFolders.Controls.Add(goToBtn);
				this.FilesFolders.Controls.Add(gap);
				//				this.FilesFolders.Controls.Add(editBtn);
				this.FilesFolders.Controls.Add(newColumn1);
				this.FilesFolders.Controls.Add(sizeLbl);
				this.FilesFolders.Controls.Add(newColumn2);
				this.FilesFolders.Controls.Add(modLbl);
				this.FilesFolders.Controls.Add(newColumn3);
				//				this.FilesFolders.Controls.Add(deleteBtn);
				this.FilesFolders.Controls.Add(endRow);	
				alternate++;
			}
		}

		private void ChangePath(object sender, CommandEventArgs e)
		{			
			if(e.CommandArgument.ToString() == "/")	// goto root
				Session["Path"] = "/baoge/";
			else if(e.CommandArgument.ToString() == "../") // go one level up in directory tree
				Session["Path"] = FTP.getParentDirectory();
			else	// add the directory name to the end of the current path
				Session["Path"] = Session["Path"].ToString() + e.CommandArgument.ToString() + "/";			
			Response.Redirect("webfile.aspx");	// prevent annoying 'repost' of data when page refreshed
		}
		
		private DirectoryInfo checkValidSessionPath()
		{
			// called by showFiles(), does checks to see if directory to be opened is valid
			DirectoryInfo mainDir;
			try
			{
				mainDir = new DirectoryInfo(Server.MapPath(Session["Path"].ToString()));
				if(mainDir.Exists == true)
					return mainDir;	// no problems
				else	// directory does not exist
					FTP.ReportError("The directory " + Server.MapPath(Session["Path"].ToString()) + " does not exist.", "Could not find a part of the path \"" + Server.MapPath(Session["Path"].ToString()) + "\".", "If you set the site root manually, try resetting it to the current directory: ./");
			}
			catch(DirectoryNotFoundException DirNotFoundEx)
			{
				FTP.ReportError("The path could not be found", DirNotFoundEx.ToString(), "Try going to <a href='default.aspx'>site root</a>.");
			}
			catch(SecurityException SecEx)
			{
				FTP.ReportError("You do not have permissions to view this directory", SecEx.ToString(), "Set the permissions for ASPNET on this directory (or contact web host)<BR>You may wish to change the root path if you can't get permissions for the root directory.");
			}
			catch(ArgumentException ArgEx)
			{
				FTP.ReportError("The path has invalid characters", ArgEx.ToString(),  "Try renaming the file and removing non-standard characters.");
			}
			catch(Exception Ex)
			{
				FTP.ReportError("Could not get Directory Information", Ex.ToString(),  "Try manually resetting the root path to ./");
			}
			return null;
		}
		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.UpBtn.Command += new System.Web.UI.WebControls.CommandEventHandler(this.ChangePath);
			this.GoRoot.Command += new System.Web.UI.WebControls.CommandEventHandler(this.ChangePath);
			
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		
	}
}
