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.Web.Caching;
using System.Xml;
using System.Runtime.Remoting.Messaging;
using System.IO;
using System.Security.Principal;
using Orciid.Core;

namespace Orciid
{
	public class export : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Label CollectionTitleLabel;
		protected System.Web.UI.WebControls.HyperLink PropertiesHyperLink;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.WebControls.CheckBox PersonalImagesCheckBox;
		protected System.Web.UI.WebControls.Button ExportButton;
		protected System.Web.UI.WebControls.DropDownList IDFieldDropDownList;
		
		private Collection coll;

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				try
				{
					coll = Collection.GetByID(Int32.Parse(Request.QueryString["id"]));
				}
				catch
				{
					coll = null;
				}
				CheckAuthorization();
				PropertiesHyperLink.NavigateUrl = String.Format("collection.aspx?id={0}", coll.ID);
				CollectionTitleLabel.Text = coll.Title;
				Field[] fields = coll.GetFields();
				IDFieldDropDownList.DataSource = fields;
				IDFieldDropDownList.DataTextField = "Label";
				IDFieldDropDownList.DataValueField = "ID";
				IDFieldDropDownList.DataBind();
			}
		}

		public override string GetHighlightedMenuItem()
		{
			return "Management_Collections";
		}

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return true;
		}
 
		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				coll = null;
				if (ViewState["cid"] != null)
					coll = Collection.GetByID((int)ViewState["cid"]);
				CheckAuthorization();
			}
		}

		protected override object SaveViewState()
		{
			if (coll != null)
				ViewState["cid"] = coll.ID;
			return base.SaveViewState();
		}

		private void CheckAuthorization()
		{
			Privilege[] privs = new Privilege[] { Privilege.ModifyImages };
			bool authorized = false;
			if (coll != null)
			{
				foreach (Privilege p in privs)
					if (Orciid.Core.User.HasPrivilege(p, coll))
					{
						authorized = true;
						break;
					}
			}
			if (!authorized)
				Response.Redirect("insufficientprivileges.aspx"); 
		}

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

		}
		#endregion

		private void ExportButton_Click(object sender, System.EventArgs e)
		{
			Field idfield;
			try
			{
				idfield = coll.GetField(Int32.Parse(IDFieldDropDownList.SelectedValue));
			}
			catch
			{
				ShowError(GetLocalString(this, "NoFieldSelected", 
					"Please select the field holding the record identifier"));
				return;
			}
			DataExchange ex = new DataExchange();
			string tempfile = null;
			try
			{
				tempfile = Path.GetTempFileName();
				TextWriter writer = File.CreateText(tempfile);
				ex.ExportToStream(writer, coll, idfield, PersonalImagesCheckBox.Checked);
				writer.Close();
				FileStream fs = File.OpenRead(tempfile);
				Response.AddHeader("Content-length", fs.Length.ToString());
				Response.ContentType = "text/xml";
				Response.AppendHeader("Content-disposition", "attachment; filename=data.xml");
				Media.Util.Tools.CopyStream(fs, Response.OutputStream);
				fs.Close();
			}
			finally
			{
				if (tempfile != null)
					File.Delete(tempfile);
			}
			Response.End();
		}
	}
}
