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 ICSharpCode.SharpZipLib.Zip;

namespace testEditor
{
	/// <summary>
	/// Summary description for importPage.
	/// </summary>
	public class importPage : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button BtnImport;
		protected System.Web.UI.WebControls.TextBox TextBoxTitle;
		protected System.Web.UI.HtmlControls.HtmlInputFile FileUpload;
		protected System.Web.UI.WebControls.RequiredFieldValidator RFValidatorFile;
		protected System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
		protected System.Web.UI.WebControls.Label lblErrMsg;
		protected System.Web.UI.WebControls.Label lblNotif;
		protected System.Web.UI.WebControls.HyperLink HLtoFile;
		protected testEditor.webheader ucHeader;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			ucHeader.pageTitle = "Learning Object Editing Toolkit";
			lblErrMsg.Text = "";
			lblNotif.Text = "";
			TextBoxTitle.Text = "";
			//Request.Form.Set("TextBoxTitle","");
			
			
		}

		#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.BtnImport.Click += new System.EventHandler(this.BtnImport_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void BtnImport_Click(object sender, System.EventArgs e)
		{
			string serverSavePath = Request.PhysicalApplicationPath + "UserFiles\\";
			string clientFileName = "";
			string serverFileName = "";

			
			if ((FileUpload.PostedFile != null) && (FileUpload.PostedFile.ContentLength > 0))
			{
				clientFileName = Path.GetFileName(FileUpload.PostedFile.FileName);
				string newFileName = "";   //use this to replace clientfilename if necessary
				
				 
				/* with encType="multipart/form-data" in form, the form data
				 * can't be accessed by TextBox.text way?
				 * so have to use request.form */
				//if (TextBoxTitle.Text != "")
				if (Request.Form["TextBoxTitle"].ToString() != "")
				{
					//use "_" to replace all spaces in filenames
					newFileName = replaceSpace(Request.Form["TextBoxTitle"]);
					serverSavePath = serverSavePath + newFileName;
				}
				else
				{
					newFileName = replaceSpace(clientFileName.Substring(0,clientFileName.IndexOf(".")));
					serverSavePath = serverSavePath + newFileName;
				}

				if (Directory.Exists(serverSavePath))
				{
					//Response.Write("The LO with the same name\"" + serverSavePath.Substring(serverSavePath.LastIndexOf("\\")+1) + "\" already exists. Please use a different name");
					lblErrMsg.Text = "The LO with the same name \"" + serverSavePath.Substring(serverSavePath.LastIndexOf("\\")+1) + "\" already exists. Please use a different name";
					return;

				}
				else
				{
					Directory.CreateDirectory(serverSavePath);
				}
				
				//attach the relevatn suffix
				serverFileName = serverSavePath + "\\" + newFileName + clientFileName.Substring(clientFileName.IndexOf("."));
					
				try
				{
					FileUpload.PostedFile.SaveAs(serverFileName);
					UnzipPackage(serverFileName);
					MoveZipFile(serverFileName,newFileName);
					//Response.Write("The file has been uploaded");
					lblNotif.Text = "The file has been uploaded";
					HLtoFile.NavigateUrl="LOedit.aspx?title=" + newFileName + "&action=view"; 
					HLtoFile.Visible= true;

				}
				catch(Exception ex)
				{
					//Response.Write("An error occurred while saving this file to server, please try again. Message: " + ex.Message);
					lblErrMsg.Text = "An error occurred while saving this file to server, please try again. <Br>Message: " + ex.Message;
				}

			}
			else
			{
				//Response.Write("Please select a zip file to upload!");
				//lblErrMsg.Text = "Please select a zip file to upload!";
			}


		}


		private void UnzipPackage(string zipPath)
		{
			ZipInputStream s = new ZipInputStream(File.OpenRead(zipPath));
		
			ZipEntry theEntry;
			while ((theEntry = s.GetNextEntry()) != null) 
			{
			
				string directoryName = Path.GetDirectoryName(theEntry.Name);
				string fileName = Path.GetFileName(theEntry.Name);
						
				if (fileName != String.Empty) 
				{
					string unzippedFile = "";
					/* When subdirectories are in the zip file*/
					if (directoryName != "")
					{
						string subDir = zipPath.Substring(0,zipPath.LastIndexOf("\\")) + "\\" + directoryName;
						if (!Directory.Exists(subDir))
						{
							Directory.CreateDirectory(subDir);
						}

						unzippedFile = subDir + "\\" + fileName;
					}
					else
					{
						unzippedFile = zipPath.Substring(0,zipPath.LastIndexOf("\\")) + "\\" + fileName; 
					}

					FileStream streamWriter = File.Create(unzippedFile);
				
					int size = 2048;
					byte[] data = new byte[2048];
					while (true) 
					{
						size = s.Read(data, 0, data.Length);
						if (size > 0) 
						{
							streamWriter.Write(data, 0, size);
						} 
						else 
						{
							break;
						}
					}
				
					streamWriter.Close();
				}
			}
			s.Close();

					
		}



		private void MoveZipFile(string zipFile, string loDirName)
		{
			string variantRoot = Request.PhysicalApplicationPath + "variants\\";
			if (!Directory.Exists(variantRoot))
			{
				Directory.CreateDirectory(variantRoot);
			}
			string variantDir = variantRoot + loDirName;
			
			if (!Directory.Exists(variantDir))
			{
				Directory.CreateDirectory(variantDir);
			}

			string variantFile = variantDir + "\\" + loDirName + "_v1.zip";
			//	zipFile.Substring(zipFile.LastIndexOf("."));

			Directory.Move(zipFile, variantFile);

			addLogEntry(variantDir,loDirName);

			//FileAttributes fa = File.GetAttributes(str);					
			
		}


		private void addLogEntry(string logPath,string loName)
		{
			string logfile = logPath + "\\" + "changes.log";
			
			/* attributes needed to be saved to log file for later use
			 * format: LO_id [client_ip] [user] version_num edit_sum  minor/major 
			 * */
			string[] attrList = new string[6];
			attrList[0] = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();

			attrList[1] = loName;
			attrList[2] = "1";  //the first version
			attrList[3] = "first version created";
			attrList[4] = "noa";   //not applicable (for the new version) minor/major
			attrList[5] = Request.UserHostAddress;

			string logline = String.Join("\t",attrList);

			StreamWriter swriter = null;						
			try
			{				
				swriter = new StreamWriter(logfile,true);
				swriter.WriteLine(logline);
			}
			catch(IOException ex)
			{
				throw ex;
			}
			finally
			{				
				swriter.Close();
			}

			
	        
		}



		private string replaceSpace(string oldStr)
		{
			char[] delim = new char[]{' '};
			string newStr = "";
			if(oldStr.IndexOf(" ") >= 0)
			{
				string[] parts = oldStr.Split(delim);
				for(int i=0; i<parts.Length; i++)
				{
					newStr += parts[i] + "_";
				}
				newStr = newStr.Substring(0,newStr.Length-1);

				return newStr;

			}

			return oldStr;
	     }


	}
}
