using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace PCSWebApp3
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class WebForm1 : Page
	{
		protected TextBox nameBox;
		protected RequiredFieldValidator validateName;
		protected Calendar calendar;
		protected TextBox eventBox;
		protected RequiredFieldValidator validateEvent;
		protected DropDownList roomList;
		protected RequiredFieldValidator validateRoom;
		protected ListBox attendeeList;
		protected RequiredFieldValidator validateAttendees;
		protected Button submitButton;
		protected ValidationSummary validationSummary;
		protected Label resultLabel;
		protected DataSet ds;
		protected DataTable eventTable;
		protected OleDbDataAdapter daAttendees;
		protected OleDbDataAdapter daRooms;
		protected DataGrid eventDetails1;
		protected DataList eventDetails2;
		protected Label edName;
		protected Label edDate;
		protected Label edRoom;
		protected Label edAttendees;
		protected OleDbDataAdapter daEvents;
		protected System.Web.UI.WebControls.Button Button1;
		public System.Data.OleDb.OleDbConnection oleDbConnection1;
	
		private void Page_Load(object sender, EventArgs e)
		{
			// Put user code to initialize the page here
			oleDbConnection1.Open();
			ds = new DataSet();
			daAttendees = new OleDbDataAdapter("SELECT * FROM Attendees", oleDbConnection1);
			daRooms = new OleDbDataAdapter("SELECT * FROM Rooms", oleDbConnection1);
			daEvents = new OleDbDataAdapter("SELECT * FROM Events", oleDbConnection1);

			daAttendees.Fill(ds, "Attendees");
			daRooms.Fill(ds, "Rooms");
			daEvents.Fill(ds, "Events");
			attendeeList.DataSource = ds.Tables["Attendees"];
			roomList.DataSource = ds.Tables["Rooms"];
			eventTable = ds.Tables["Events"];
			eventDetails1.DataSource = eventTable;
			eventDetails2.DataSource = eventTable;

			if (!IsPostBack)
			{
				DateTime trialDate = DateTime.Now;
				calendar.SelectedDate = getFreeDate(trialDate);
				DataBind();
			}
			else
			{
				eventDetails1.DataBind();
				eventDetails2.DataBind();
			}
			oleDbConnection1.Close();
		}

		#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.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
			this.calendar.SelectionChanged += new System.EventHandler(this.calendar_SelectionChanged);
			this.calendar.DayRender += new System.Web.UI.WebControls.DayRenderEventHandler(this.calendar_DayRender);
			this.submitButton.Click += new System.EventHandler(this.submitButton_Click);
			this.Button1.Click += new System.EventHandler(this.Button1_Click);
			this.eventDetails1.SelectedIndexChanged += new System.EventHandler(this.eventDetails1_SelectedIndexChanged);
			// 
			// oleDbConnection1
			// 
			this.oleDbConnection1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Password=\"\";User ID=Admin;Data Source=C:\\Inetpub" +
				"\\wwwroot\\PCSWebApp3\\PCSWebApp3.mdb";
			this.oleDbConnection1.InfoMessage += new System.Data.OleDb.OleDbInfoMessageEventHandler(this.oleDbConnection1_InfoMessage);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void submitButton_Click(object sender, EventArgs e)
		{
			if (IsValid)
			{
				String attendees = "";
				foreach (ListItem attendee in attendeeList.Items)
				{
					if (attendee.Selected)
					{
						attendees += attendee.Text + " (" + attendee.Value + "), ";
					}
				}
				attendees += " and " + nameBox.Text;
				String dateString = calendar.SelectedDate.Date.Date.ToShortDateString();
				String oleDbCommand = "INSERT INTO Events (Name, Room, " +
										"AttendeeList, EventDate) VALUES ('" +
										eventBox.Text + "', '" +
										roomList.SelectedItem.Value + "', '" +
										attendees + "', #" + dateString + "#)";
				OleDbCommand insertCommand = new OleDbCommand(oleDbCommand, oleDbConnection1);
				oleDbConnection1.Open();
				int queryResult = insertCommand.ExecuteNonQuery();
				if (queryResult == 1)
					{
						resultLabel.Text = "Event Added.";
						daEvents = new OleDbDataAdapter("SELECT * FROM Events", oleDbConnection1);
						ds.Clear();
						daEvents.Fill(ds, "Events");
						eventTable = ds.Tables["Events"];
						calendar.SelectedDate = getFreeDate(calendar.SelectedDate.AddDays(1));
						eventDetails1.DataBind();
						eventDetails2.DataBind();
					}
					else
					{
						resultLabel.Text = "Event not added due to DB access problem.";
					}
				oleDbConnection1.Close();
			}
		}

		private DateTime getFreeDate(DateTime trialDate)
		{
			if (eventTable.Rows.Count > 0)
			{
				DateTime testDate;
				bool trialDateOK = false;
				while (!trialDateOK)
				{
					trialDateOK = true;
					foreach (DataRow testRow in eventTable.Rows)
					{
						testDate = (DateTime)testRow["EventDate"];
						if (testDate.Date == trialDate.Date)
						{
							trialDateOK = false;
							trialDate = trialDate.AddDays(1);
						}
					}
				}
			}
			return trialDate;
		}

		private void calendar_SelectionChanged(object sender, EventArgs e)
		{
			DateTime trialDate = calendar.SelectedDate;
			calendar.SelectedDate = getFreeDate(trialDate);
		}

		protected void calendar_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
		{
			if (eventTable.Rows.Count > 0)
			{
				DateTime testDate;
				foreach (DataRow testRow in eventTable.Rows)
				{
					testDate = (DateTime)testRow["EventDate"];
					if (testDate.Date == e.Day.Date)
					{
						e.Cell.BackColor = Color.Red;
					}
				}
			}
		}

		protected void eventDetails2_SelectedIndexChanged(object sender, EventArgs e)
		{
			eventDetails2.DataBind();
			DataRow selectedEventRow = eventTable.Rows[eventDetails2.SelectedIndex];
			edName.Text = (string)selectedEventRow["Name"];
			edDate.Text = "<b>Date:</b> " + ((DateTime)selectedEventRow["EventDate"]).ToLongDateString();
			edAttendees.Text = "<b>Attendees:</b> " + (string)selectedEventRow["AttendeeList"];
			DataRow selectedEventRoomRow = ds.Tables["Rooms"].Rows[(int)selectedEventRow["Room"] - 1];
			edRoom.Text = "<b>Room:</b> " + selectedEventRoomRow["Room"];
		
		}

		private void oleDbConnection1_InfoMessage(object sender, OleDbInfoMessageEventArgs e)
		{
		
		}

		private void eventDetails1_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		private void Button1_Click(object sender, System.EventArgs e)
		{
			eventDetails2.DataBind();
			validationSummary.Enabled = false;
            string cID = eventTable.Rows[eventDetails2.SelectedIndex]["ID"].ToString();
			oleDbConnection1.Open();
			if (new OleDbCommand("DELETE FROM Events WHERE ID = " + cID, oleDbConnection1).ExecuteNonQuery() == 1) 
			{
				daEvents = new OleDbDataAdapter("SELECT * FROM Events", oleDbConnection1);
				ds.Clear();
				daEvents.Fill(ds, "Events");
				daRooms.Fill(ds, "Rooms");
				eventTable = ds.Tables["Events"];
				eventDetails2.DataSource = eventTable;
				eventDetails2.DataBind();
				calendar.SelectedDate = getFreeDate(calendar.SelectedDate.AddDays(1));
				if (eventDetails2.SelectedIndex > eventDetails2.Items.Count - 1)
				{
					eventDetails2.EditItemIndex = eventDetails2.SelectedIndex -1;
				}
				if (eventDetails2.EditItemIndex == -1)
				{
					edDate.Text = "";
					edAttendees.Text = "";
					edRoom.Text = ":";
					resultLabel.Text = "Record deleted.";
				}
				else
				{
					DataRow selectedEventRow = eventTable.Rows[eventDetails2.EditItemIndex];
					edName.Text = (string)selectedEventRow["Name"];
					edDate.Text = "<b>Date:</b> " + ((DateTime)selectedEventRow["EventDate"]).ToLongDateString();
					edAttendees.Text = "<b>Attendees:</b> " + (string)selectedEventRow["AttendeeList"];
					DataRow selectedEventRoomRow = ds.Tables["Rooms"].Rows[(int)selectedEventRow["Room"] - 1];
					edRoom.Text = "<b>Room:</b> " + selectedEventRoomRow["Room"];
				}
			}
			else
			{
				resultLabel.Text = "DELETE RECORD FAILED.";
			}
			eventDetails1.DataBind();
			eventDetails1.DataSource = eventTable;
			/* get list entry to bold */
			eventDetails2.SelectedIndex = eventDetails2.EditItemIndex;
			/* get detail about event to refresh */
			eventDetails2.DataBind();
			oleDbConnection1.Close();
		}
	}
}
