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 Orciid.Core;

namespace Orciid
{
	public class Agreements : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Repeater AgreementsRepeater;
		protected System.Web.UI.WebControls.Button AgreeButton;

		private Hashtable collids = new Hashtable();
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DescriptionParagraph;
		private string gotourl = null;

		private void Page_Load(object sender, System.EventArgs e)
		{			
			if (!IsPostBack)
				gotourl = Request.QueryString["go"];
			Orciid.Core.User tempuser = Session["TempUser"] as Orciid.Core.User;
			if (tempuser != null)
				tempuser.Activate(Request.UserHostAddress);
		}

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				if (ViewState["collids"] is Hashtable)
					collids = (Hashtable)ViewState["collids"];
				gotourl = (string)ViewState["gotourl"];
			}
		}

		protected override object SaveViewState()
		{
			ViewState["collids"] = collids;
			ViewState["gotourl"] = gotourl;
			return base.SaveViewState();
		}

		protected void CheckedChangedAgreementCheckBox(object sender, System.EventArgs e)
		{
			CheckBox checkbox = sender as CheckBox;
			if (checkbox.Checked)
			{
				Orciid.Core.User user = Orciid.Core.User.CurrentUser();
				int id = (int)collids[checkbox.Parent.UniqueID];
				if (user is Orciid.Core.AnonymousUser)
				{
					ArrayList guestaccepted = (ArrayList)Session["GuestAcceptedAgreements"];
					if (guestaccepted == null)
						guestaccepted = new ArrayList();
					if (!guestaccepted.Contains(id))
						guestaccepted.Add(id);
					Session["GuestAcceptedAgreements"] = guestaccepted;
				}
				else
				{
					Collection coll = Collection.GetByID(id);
					coll.AcceptUsageAgreement(user);
				}
			}
		}

		protected void DataBindAgreementCheckBox(object sender, System.EventArgs e)
		{
			CheckBox checkbox = sender as CheckBox;
			collids[checkbox.Parent.UniqueID] = ((Collection)((RepeaterItem)checkbox.Parent).DataItem).ID;
		}

		protected void DataBindAgreementTextBox(object sender, System.EventArgs e)
		{
			TextBox textbox = sender as TextBox;
			textbox.Text = ((Collection)((RepeaterItem)textbox.Parent).DataItem).UsageAgreement;
		}

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

		public override bool HasLeftMenu()
		{
			return false;
		}

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			if (user == null)
			{
				Orciid.Core.User tempuser = Session["TempUser"] as Orciid.Core.User;
				return (tempuser != null);
			}
			else
				return true;
		}
 
		#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 System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);

		}
		#endregion

		private void Page_PreRender(object sender, System.EventArgs e)
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			ArrayList list = new ArrayList();
			ArrayList guestaccepted = (ArrayList)Session["GuestAcceptedAgreements"];
			foreach (Collection coll in Collection.GetCollections())
				if (coll.UsageAgreement != null)
				{
					if (user is Orciid.Core.AnonymousUser)
					{	
						if (guestaccepted == null || !guestaccepted.Contains(coll.ID))
							list.Add(coll);
					}
					else if (!coll.HasAcceptedUsageAgreement(user)) 
						list.Add(coll);
				}
			if (list.Count == 0)
			{
				if (Session["CurrentUser"] == null)
				{
					Session["CurrentUser"] = Session["TempUser"];
					Session["TempUser"] = null;
				}

				// user is now logged in, check for saved searches and see if there are
				// any new search results

				if (user != null)
				{
					foreach (SavedSearch search in SavedSearch.GetAll(user))
						search.CheckForNewImages();
				}

				// redirect to target page

				if (gotourl != null)
					Response.Redirect(gotourl);
				else
				{
					string page = "announcements";

					if (user != null)
					{
						Properties props = Properties.GetProperties(user);
						page = props.Get("uistartpage", page);				
					}

					// if new announcement has been posted since last login, 
					// force announcement page
					if (user.PrevLastAuthenticated > DateTime.MinValue &&
						user.PrevLastAuthenticated < Announcement.GetLastAnnouncementDateTime() &&
                        page != "announcements")
						Response.Redirect("announcements.aspx?continue=" + page);
					else
						Response.Redirect(page + ".aspx"); 
				}
			}
			AgreementsRepeater.DataSource = list;
			AgreementsRepeater.DataBind();	
		}

	}
}
