Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.Text
Imports DayPilot.Utils
Imports DayPilot.Web.Ui.Enums
Imports DayPilot.Web.Ui.Events
Imports DayPilot.Web.Ui.Events.Bubble
Imports DayPilot.Web.Ui.Events.Calendar
Imports DayPilot.Web.Ui.Recurrence

Partial Public Class Calendar_RecurrentEvents
	Inherits System.Web.UI.Page

	Private table As DataTable

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'		#Region "Data loading initialization"
		If Session("Recurrence") Is Nothing Then
			Session("Recurrence") = GetData()
		End If
		table = DirectCast(Session("Recurrence"), DataTable)
		DayPilotCalendar1.DataSource = Session("Recurrence")
		DayPilotNavigator1.DataSource = Session("Recurrence")
'		#End Region

		If Not IsPostBack Then
			DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek()
			DataBind()
		End If
	End Sub

	Private Function GetData() As DataTable

		Dim dt As DataTable
		dt = New DataTable()
		dt.Columns.Add("start", GetType(Date))
		dt.Columns.Add("end", GetType(Date))
		dt.Columns.Add("name", GetType(String))
		dt.Columns.Add("id", GetType(String))
		dt.Columns.Add("recurrence", GetType(String))

		Dim dr As DataRow

		Dim start As Date = Week.FirstDayOfWeek().AddHours(15)
		' starting on the first day of this week today at 15:00, repeated every week, five times
		Dim rule As RecurrenceRule = RecurrenceRule.FromDateTime("1", start).Weekly().Times(5)

		dr = dt.NewRow()
		dr("id") = 1
		dr("start") = start
		dr("end") = start.AddHours(1)
		dr("name") = "Every week"
		dr("recurrence") = rule.Encode()
		dt.Rows.Add(dr)

		Dim start2 As Date = Week.FirstDayOfWeek().AddHours(10)
		' starting on the first day of this week at 10:00, repeated every day for one month
		'RecurrenceRule rule2 = RecurrenceRule.FromDateTime("2", start2).Daily().Until(start2.AddDays(31));
		Dim rule2 As RecurrenceRule = RecurrenceRule.FromDateTime("2", start2).Daily(2).Times(2)

		dr = dt.NewRow()
		dr("id") = 2
		dr("start") = start2
		dr("end") = start2.AddHours(1)
		dr("name") = "Every day"
		dr("recurrence") = rule2.Encode()
		dt.Rows.Add(dr)

		Dim start3 As Date = Week.FirstDayOfWeek().AddDays(1).AddHours(13)
		dr = dt.NewRow()
		dr("id") = 3
		dr("start") = start3
		dr("end") = start3.AddHours(1)
		dr("name") = "By hour (custom)"
		dt.Rows.Add(dr)

		dt.PrimaryKey = New DataColumn() { dt.Columns("id") }

		Return dt
	End Function

	Protected Sub DayPilotCalendar1_EventMove(ByVal sender As Object, ByVal e As EventMoveEventArgs)

'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)

		' recurrent event but no exception
		If e.Recurrent AndAlso Not e.RecurrentException Then
'NOTE: The variable master was renamed since Visual Basic does not handle local variables named the same as class members well:
			Dim master_Renamed As DataRow = table.Rows.Find(e.RecurrentMasterId)

			dr = table.NewRow()
			dr("id") = Guid.NewGuid().ToString()
			dr("name") = master_Renamed("name")
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			dr("recurrence") = RecurrenceRule.EncodeExceptionModified(e.RecurrentMasterId, e.OldStart)
			table.Rows.Add(dr)
			table.AcceptChanges()
		' recurrent exception or regular event
		ElseIf dr IsNot Nothing Then
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			table.AcceptChanges()
		End If

'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.UpdateWithMessage("Event moved.")
	End Sub

	Protected Sub DayPilotCalendar1_EventMenuClick(ByVal sender As Object, ByVal e As EventMenuClickEventArgs)
		If e.Command = "Delete" Then
'			#Region "Simulation of database update"

			Dim dr As DataRow = table.Rows.Find(e.Id)

			If e.Recurrent AndAlso Not e.RecurrentException Then
				dr = table.NewRow()
				dr("id") = Guid.NewGuid().ToString()
				dr("start") = e.Start
				dr("end") = e.End
				dr("recurrence") = RecurrenceRule.EncodeExceptionDeleted(e.RecurrentMasterId, e.Start)
				table.Rows.Add(dr)
				table.AcceptChanges()
			ElseIf e.Recurrent AndAlso e.RecurrentException AndAlso dr IsNot Nothing Then
				table.Rows.Remove(dr)
				table.AcceptChanges()
			ElseIf dr IsNot Nothing Then
				table.Rows.Remove(dr)
				table.AcceptChanges()
			End If

'			#End Region

			DayPilotCalendar1.DataBind()
			DayPilotCalendar1.Update()
		End If
	End Sub
	Protected Sub DayPilotCalendar1_TimeRangeSelected(ByVal sender As Object, ByVal e As TimeRangeSelectedEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.NewRow()
		dr("start") = e.Start
		dr("end") = e.End
		dr("id") = Guid.NewGuid().ToString()
		dr("name") = "New event"

		table.Rows.Add(dr)
		table.AcceptChanges()
'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update("New event created.")
	End Sub

	Protected Sub DayPilotCalendar1_EventResize(ByVal sender As Object, ByVal e As EventResizeEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)

		If e.Recurrent AndAlso Not e.RecurrentException Then
'NOTE: The variable master was renamed since Visual Basic does not handle local variables named the same as class members well:
			Dim master_Renamed As DataRow = table.Rows.Find(e.RecurrentMasterId)

			dr = table.NewRow()
			dr("id") = Guid.NewGuid().ToString()
			dr("recurrence") = RecurrenceRule.EncodeExceptionModified(e.RecurrentMasterId, e.OldStart)
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			dr("name") = master_Renamed("name")
			table.Rows.Add(dr)
			table.AcceptChanges()
		ElseIf dr IsNot Nothing Then
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			table.AcceptChanges()
		End If

'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update("Event resized")
	End Sub

	Protected Sub DayPilotCalendar1_EventClick(ByVal sender As Object, ByVal e As EventClickEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)
		If dr IsNot Nothing Then
			dr("name") = "Event clicked at " & Date.Now
			table.AcceptChanges()
		End If

'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update()
	End Sub
	Protected Sub DayPilotCalendar1_EventEdit(ByVal sender As Object, ByVal e As EventEditEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)
		If dr IsNot Nothing Then
			dr("name") = e.NewText
			table.AcceptChanges()
		End If

'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update("Event text changed.")
	End Sub
	Protected Sub DayPilotCalendar1_BeforeEventRender(ByVal sender As Object, ByVal e As BeforeEventRenderEventArgs)
	End Sub


	Protected Sub DayPilotCalendar1_EventDelete(ByVal sender As Object, ByVal e As EventDeleteEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)

		If e.Recurrent Then
			If e.RecurrentException Then ' replace this exception with a deleted exception
				If dr IsNot Nothing Then
					' save the original start
					Dim start As Date = RecurrenceRule.DecodeStart(DirectCast(dr("recurrence"), String))

					' delete the "modified" exception
					table.Rows.Remove(dr)
					table.AcceptChanges()

					' add "deleted" exception
					dr = table.NewRow()
					dr("id") = Guid.NewGuid().ToString()
					dr("start") = start
					dr("end") = start
					dr("recurrence") = RecurrenceRule.EncodeExceptionDeleted(e.RecurrentMasterId, start)
					table.Rows.Add(dr)
					table.AcceptChanges()
				End If

			Else
				' not an exception, look for the request
				Dim which As String = CStr(e.Data("which"))
				Select Case which
					Case "this"
						' add "deleted" exception
						dr = table.NewRow()
						dr("id") = Guid.NewGuid().ToString()
						dr("start") = e.Start
						dr("end") = e.End
						dr("recurrence") = RecurrenceRule.EncodeExceptionDeleted(e.RecurrentMasterId, e.Start)
						table.Rows.Add(dr)
						table.AcceptChanges()

					Case "series"
						' delete the master
'NOTE: The variable master was renamed since Visual Basic does not handle local variables named the same as class members well:
						Dim master_Renamed As DataRow = table.Rows.Find(e.RecurrentMasterId)
						table.Rows.Remove(master_Renamed)

						' delete all exceptions
						Dim prefix As String = RecurrenceRule.Prefix(e.RecurrentMasterId)
						Dim rows() As DataRow = table.Select(String.Format("recurrence like '{0}%'", prefix))
						For Each r As DataRow In rows
							table.Rows.Remove(r)
						Next r
						table.AcceptChanges()
				End Select

			End If
		Else
			If dr IsNot Nothing Then
				table.Rows.Remove(dr)
				table.AcceptChanges()
			End If
		End If

'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update("Event deleted.")
	End Sub

	Protected Sub DayPilotCalendar1_EventSelect(ByVal sender As Object, ByVal e As DayPilotEventArgs)
		DayPilotCalendar1.Update()
	End Sub


	Protected Sub DayPilotCalendar1_BeforeHeaderRender(ByVal sender As Object, ByVal e As BeforeHeaderRenderEventArgs)
	End Sub

	Protected Sub DayPilotBubble1_RenderContent(ByVal sender As Object, ByVal e As RenderEventArgs)
		If TypeOf e Is RenderEventBubbleEventArgs Then
			Dim re As RenderEventBubbleEventArgs = TryCast(e, RenderEventBubbleEventArgs)

			Dim sb As New StringBuilder()
			sb.AppendFormat("<b>{0}</b><br />", re.Text)
			sb.AppendFormat("Start: {0}<br />", re.Start)
			sb.AppendFormat("End: {0}<br />", re.End)

			're.InnerHTML = "<b>Event details</b><br />Here is the right place to show details about the event with ID: " + re.Value + ". This text is loaded dynamically from the server.<br/>";
			re.InnerHTML = sb.ToString()
		ElseIf TypeOf e Is RenderTimeBubbleEventArgs Then
			Dim re As RenderTimeBubbleEventArgs = TryCast(e, RenderTimeBubbleEventArgs)
			e.InnerHTML = "<b>Time header details</b><br />From:" & re.Start & "<br />To: " & re.End
		ElseIf TypeOf e Is RenderCellBubbleEventArgs Then
			Dim re As RenderCellBubbleEventArgs = TryCast(e, RenderCellBubbleEventArgs)
			e.InnerHTML = "<b>Cell details</b><br />Column:" & re.ResourceId & "<br />From:" & re.Start & "<br />To: " & re.End
		End If
	End Sub

	Protected Sub DayPilotCalendar1_TimeRangeDoubleClick(ByVal sender As Object, ByVal e As TimeRangeDoubleClickEventArgs)

'		#Region "Simulation of database update"
		Dim dr As DataRow = table.NewRow()
		dr("start") = e.Start
		dr("end") = e.End
		dr("id") = Guid.NewGuid().ToString()
		dr("name") = "New event"

		table.Rows.Add(dr)
		table.AcceptChanges()
'		#End Region

		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update("New event created.")
	End Sub

	Protected Sub DayPilotCalendar1_TimeRangeMenuClick(ByVal sender As Object, ByVal e As TimeRangeMenuClickEventArgs)
		If e.Command = "Insert" Then
'			#Region "Simulation of database update"

			Dim dr As DataRow = table.NewRow()
			dr("start") = e.Start
			dr("end") = e.End
			dr("id") = Guid.NewGuid().ToString()
			dr("name") = "New event"

			table.Rows.Add(dr)
			table.AcceptChanges()
'			#End Region

			DayPilotCalendar1.DataBind()
			DayPilotCalendar1.Update()
		End If

	End Sub
	Protected Sub DayPilotCalendar1_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
		Select Case e.Command
			Case "previous"
				DayPilotCalendar1.StartDate = DayPilotCalendar1.StartDate.AddDays(-7)
				DayPilotCalendar1.DataBind()
				DayPilotCalendar1.Update(CallBackUpdateType.Full)
			Case "navigate"
				Dim start As Date = CDate(e.Data("start"))
				Dim [end] As Date = CDate(e.Data("end"))

				DayPilotCalendar1.StartDate = start
				'DayPilotCalendar1.Days = (int) (end - start).TotalDays;

				DayPilotCalendar1.DataBind()
				DayPilotCalendar1.Update(CallBackUpdateType.Full)
			Case "refresh"
				DayPilotCalendar1.DataBind()
				DayPilotCalendar1.Update()
		End Select


	End Sub
	Protected Sub DayPilotNavigator1_VisibleRangeChanged(ByVal sender As Object, ByVal e As EventArgs)
		DayPilotNavigator1.DataBind()
	End Sub

	Protected Sub DayPilotCalendar1_BeforeCellRender(ByVal sender As Object, ByVal e As BeforeCellRenderEventArgs)
		'e.BackgroundColor = "#a2a2a2";
	End Sub

	Protected Sub DayPilotCalendar1_HeaderClick(ByVal sender As Object, ByVal e As HeaderClickEventArgs)
	End Sub

	Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
		GridView1.DataSource = RecurrenceExpander.Expand(table, "recurrence", "start", "end", "id", "master", DayPilotCalendar1.StartDate, DayPilotCalendar1.EndDate)
		GridView2.DataSource = table
		DataBind()

	End Sub

	Protected Sub DayPilotCalendar1_OnBeforeEventRecurrence(ByVal ea As BeforeEventRecurrenceEventArgs)
		Dim list As New List(Of Date)()
		For i As Integer = 1 To 4
			list.Add(ea.Start.AddHours(i))
		Next i
		ea.Rule = RecurrenceRule.FromList(list)
	End Sub
End Class
