Imports System
Imports System.Data
Imports System.Drawing.Imaging
Imports System.IO
Imports DayPilot.Utils
Imports DayPilot.Web.Ui.Enums
Imports DayPilot.Web.Ui.Events
Imports DayPilot.Web.Ui.Events.Bubble
Imports DayPilot.Web.Ui.Recurrence

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

	Private table As DataTable

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
		initData()
		If Not IsPostBack Then
			DayPilotMonth1.UpdateWithMessage("Start: " & DayPilotMonth1.VisibleStart & " end: " & DayPilotMonth1.VisibleEnd)
			DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
			DataBind()
		End If
	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 dr IsNot Nothing Then
				table.Rows.Remove(dr)
				table.AcceptChanges()
			End If
'			#End Region

			DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
			DayPilotMonth1.DataBind()
			DayPilotMonth1.Update()
		End If
	End Sub
	Protected Sub DayPilotMonth1_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()

			DayPilotMonth1.UpdateWithMessage("Recurrent event exception added.")
		' recurrent exception or regular event
		ElseIf dr IsNot Nothing Then
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			table.AcceptChanges()

			DayPilotMonth1.UpdateWithMessage("Event moved.")
		Else
			DayPilotMonth1.UpdateWithMessage("No update.")
		End If

'		#End Region

		DayPilotMonth1.UpdateWithMessage("Update. Start: " & DayPilotMonth1.VisibleStart & " end: " & DayPilotMonth1.VisibleEnd)
		DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
		DayPilotMonth1.DataBind()


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

		Dim dr As DataRow = table.Rows.Find(e.Id)
'        
'        if (dr != null)
'        {
'            dr["start"] = e.NewStart;
'            dr["end"] = e.NewEnd;
'            table.AcceptChanges();
'        }
'        

		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

		DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
		DayPilotMonth1.DataBind()
		DayPilotMonth1.UpdateWithMessage("Event resized")

	End Sub

	Protected Sub DayPilotMonth1_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

		DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
		DayPilotMonth1.DataBind()
		DayPilotMonth1.Update()
	End Sub
	Protected Sub DayPilotMonth1_BeforeEventRender(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.Month.BeforeEventRenderEventArgs)
		If e.Id = "12" Then
			e.ContextMenuClientName = "menu2"
		End If
	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)
			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."
		End If
	End Sub

	Protected Sub DayPilotMonth1_Command(ByVal sender As Object, ByVal e As CommandEventArgs)

		Select Case e.Command
			Case "navigate"
				DayPilotMonth1.StartDate = CDate(e.Data("start"))
				DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
				DayPilotMonth1.DataBind()
				DayPilotMonth1.Update()
			Case "filter"
				DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
				DayPilotMonth1.DataBind()
				DayPilotMonth1.Update()
			Case "refresh"
				DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, CStr(DayPilotMonth1.ClientState("filter")))
				DayPilotMonth1.DataBind()
				DayPilotMonth1.Update()

		End Select

	End Sub

	''' <summary>
	''' This method should normally load the data from the database.
	''' We will load our copy from a Session, just simulating a database.
	''' </summary>
	''' <param name="start"></param>
	''' <param name="end"></param>
	''' <param name="filter"></param>
	''' <returns></returns>
	Private Function getData(ByVal start As Date, ByVal [end] As Date, ByVal filter As String) As DataTable
		Dim [select] As String
		If String.IsNullOrEmpty(filter) Then
			[select] = String.Format("NOT (([end] <= '{0:s}') OR ([start] >= '{1:s}'))", start, [end], filter)
		Else
			[select] = String.Format("NOT (([end] <= '{0:s}') OR ([start] >= '{1:s}')) and [name] like '%{2}%'", start, [end], filter)
'            throw new Exception(select);
		End If


		Dim rows() As DataRow = table.Select([select])

		Dim filtered As DataTable = table.Clone()

		For Each r As DataRow In rows
			filtered.ImportRow(r)
		Next r

		Return filtered
	End Function

	''' <summary>
	''' Make sure a copy of the data is in the Session so users can try changes on their own copy.
	''' </summary>
	Private Sub initData()
		If Session("MonthRecurrence") Is Nothing Then
			Session("MonthRecurrence") = GetData_Renamed()
		End If

		table = DirectCast(Session("MonthRecurrence"), DataTable)
	End Sub

	Protected Sub DayPilotMonth1_BeforeCellRender(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.Month.BeforeCellRenderEventArgs)
		e.CssClass = If(Week.WeekNrISO8601(e.Start) Mod 2 = 0, "even", "odd")
	End Sub

	Protected Sub DayPilotMonth1_EventClick(ByVal sender As Object, ByVal e As EventClickEventArgs)
	End Sub

'NOTE: The method GetData was renamed since Visual Basic does not allow same-signature methods with the same name:
	Private Function GetData_Renamed() 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
		Dim rule2 As RecurrenceRule = RecurrenceRule.FromDateTime("2", start2).Daily().Until(start2.AddDays(31))

		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)

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

		Return dt
	End Function

End Class
