Imports System
Imports System.Data
Imports DayPilot.Utils
Imports DayPilot.Web.Ui.Enums
Imports DayPilot.Web.Ui.Events.Bubble

Partial Public Class Scheduler_Zooming
	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
			Dim firstDay As New Date(Date.Today.Year, Date.Today.Month, 1)
			DayPilotScheduler1.StartDate = New Date(Date.Today.Year, 1, 1)
			DayPilotScheduler1.Days = Year.Days(firstDay.Year)

			adjustCellLayout()

			DayPilotScheduler1.SetScrollX(firstDay)
			setDataSourceAndBind()
		End If
	End Sub

	Private Sub setDataSourceAndBind()
		' ensure that filter is loaded
		Dim filter As String = CStr(DayPilotScheduler1.ClientState("filter"))
		DayPilotScheduler1.DataSource = getData(DayPilotScheduler1.StartDate, DayPilotScheduler1.EndDate, filter)
		DayPilotScheduler1.DataBind()

	End Sub

	Protected Sub DayPilotScheduler1_BeforeTimeHeaderRender(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.BeforeTimeHeaderRenderEventArgs)
		If e.Level = 0 Then
			Dim days As Integer = CInt(Math.Truncate(Math.Floor((e.End - e.Start).TotalDays)))

			Dim outStart As Date = Date.MinValue
			Dim outDays As Integer

			Select Case DayPilotScheduler1.CellGroupBy
				Case GroupByEnum.Hour ' day, switch to week
					outStart = Week.FirstDayOfWeek(e.Start, DayOfWeek.Monday)
					outDays = 7
				Case GroupByEnum.Day ' week, switch to month
					outStart = New Date(e.Start.Year, e.Start.Month, 1)
					outDays = Date.DaysInMonth(e.Start.Year, e.Start.Month)
				Case GroupByEnum.Week ' month, switch to year
					outStart = New Date(e.Start.Year, 1, 1)
					outDays = If(Date.IsLeapYear(e.Start.Year), 366, 365)
				Case GroupByEnum.Month ' year, dont switch
					outDays = 0
				Case Else
					Throw New ArgumentOutOfRangeException()
			End Select

			If days >= 1 Then ' do not zoom into greater detail than one day
				e.InnerHTML = String.Format("<a href='javascript:dps1.commandCallBack(""goto"", {{ start:""{0}"", days:{1} }})' style='color:black' title='Zoom in'>{2}</a>", e.Start.ToString("s"), days, e.InnerHTML)
			End If

			If outDays > 0 Then ' do not zoom out if we see the whole year
				e.InnerHTML += String.Format(" (<a href='javascript:dps1.commandCallBack(""goto"", {{ start: ""{0}"", days: {1} }})' style='color:black' title='Zoom out'>up</a>)", outStart.ToString("s"), outDays)
			End If
		End If
	End Sub

	Private Sub adjustCellLayout()
		Dim days As Integer = DayPilotScheduler1.Days

		If days > 31 Then ' year
			DayPilotScheduler1.CellGroupBy = GroupByEnum.Month
			DayPilotScheduler1.CellDuration = 1440
			DayPilotScheduler1.CellWidth = 20
		ElseIf days >= 28 Then ' month
			DayPilotScheduler1.CellGroupBy = GroupByEnum.Week
			DayPilotScheduler1.CellDuration = 1440
			DayPilotScheduler1.CellWidth = 60
		ElseIf days > 1 Then ' week
			DayPilotScheduler1.CellGroupBy = GroupByEnum.Day
			DayPilotScheduler1.CellDuration = 60
			DayPilotScheduler1.CellWidth = 60
		Else ' day
			DayPilotScheduler1.CellGroupBy = GroupByEnum.Hour
			DayPilotScheduler1.CellDuration = 15
			DayPilotScheduler1.CellWidth = 60
		End If
	End Sub

	Protected Sub DayPilotScheduler1_EventMove(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMoveEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)
		If dr IsNot Nothing Then
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			dr("column") = e.NewResource
			table.AcceptChanges()
		Else ' moved from outside
			dr = table.NewRow()
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			dr("id") = e.Id
			dr("name") = e.Text
			dr("column") = e.NewResource

			table.Rows.Add(dr)
			table.AcceptChanges()
		End If

'		#End Region

		setDataSourceAndBind()
		DayPilotScheduler1.Update("Event moved.")
	End Sub
	Protected Sub DayPilotScheduler1_EventResize(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventResizeEventArgs)
'		#Region "Simulation of database update"

		Dim dr As DataRow = table.Rows.Find(e.Id)
		If dr IsNot Nothing Then
			dr("start") = e.NewStart
			dr("end") = e.NewEnd
			table.AcceptChanges()
		End If

'		#End Region

		setDataSourceAndBind()
		DayPilotScheduler1.Update()
	End Sub
	Protected Sub DayPilotScheduler1_TimeRangeSelected(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.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"
		dr("column") = e.Resource

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

		setDataSourceAndBind()
		DayPilotScheduler1.Update(String.Format("New event created."))
	End Sub
	Protected Sub DayPilotScheduler1_EventEdit(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.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

		setDataSourceAndBind()
		DayPilotScheduler1.Update()
	End Sub

	Protected Sub DayPilotScheduler1_BeforeEventRender(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.Scheduler.BeforeEventRenderEventArgs)
		If e.Id = "11" Then
			e.ContextMenuClientName = "cmSpecial"
			e.EventMoveEnabled = False
			e.EventResizeEnabled = False
			e.EventClickEnabled = False
			e.DurationBarColor = "red"
			e.BackgroundColor = "lightyellow"
		End If
	End Sub

	Protected Sub DayPilotScheduler1_EventMenuClick(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMenuClickEventArgs)
		Select Case e.Command
			Case "Delete"
'				#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
		End Select

		setDataSourceAndBind()
		DayPilotScheduler1.Update()
	End Sub

	Protected Sub DayPilotScheduler1_BeforeResHeaderRender(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.Scheduler.BeforeResHeaderRenderEventArgs)
	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.<br/><a href='http://www.google.com'>Google</a>"
		ElseIf TypeOf e Is RenderResourceBubbleEventArgs Then
			Dim re As RenderResourceBubbleEventArgs = TryCast(e, RenderResourceBubbleEventArgs)
			e.InnerHTML = "<b>Resource header details</b><br />Value: " & re.ResourceId
		ElseIf TypeOf e Is RenderCellBubbleEventArgs Then
			Dim re As RenderCellBubbleEventArgs = TryCast(e, RenderCellBubbleEventArgs)
			e.InnerHTML = "<b>Cell details</b><br />Resource:" & re.ResourceId & "<br />From:" & re.Start & "<br />To: " & re.End
		End If
	End Sub

	Protected Sub DayPilotScheduler1_Command(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.CommandEventArgs)
		Select Case e.Command
			Case "next"
				DayPilotScheduler1.StartDate = DayPilotScheduler1.StartDate.AddYears(1)
				DayPilotScheduler1.Days = Year.Days(DayPilotScheduler1.StartDate.Year)
				DayPilotScheduler1.ScrollX = 0
				adjustCellLayout()
			Case "previous"
				DayPilotScheduler1.StartDate = DayPilotScheduler1.StartDate.AddYears(-1)
				DayPilotScheduler1.Days = Year.Days(DayPilotScheduler1.StartDate.Year)
				DayPilotScheduler1.ScrollX = 0
				adjustCellLayout()
			Case "this"
				DayPilotScheduler1.StartDate = New Date(Date.Today.Year, 1, 1)
				DayPilotScheduler1.Days = Year.Days(DayPilotScheduler1.StartDate.Year)
				DayPilotScheduler1.ScrollX = 0
				adjustCellLayout()
			Case "goto"
				DayPilotScheduler1.StartDate = CDate(e.Data("start"))
				DayPilotScheduler1.Days = e.Data("days").ToInt32()
				DayPilotScheduler1.ScrollX = 0
				If IsTodayInRange() Then
					DayPilotScheduler1.SetScrollX(Date.Today)
				Else
					DayPilotScheduler1.ScrollX = 0
				End If
				adjustCellLayout()
			Case "refresh"
				' just rebind
			Case "filter"
				'string filter = (string)e.Data;
				'DayPilotScheduler1.DataSource = getData(DayPilotScheduler1.StartDate, DayPilotScheduler1.EndDate.AddDays(1), filter);
				setDataSourceAndBind()
				DayPilotScheduler1.DataBind()
				DayPilotScheduler1.Update(CallBackUpdateType.EventsOnly)
				Return ' note that the binding done inside the case section here
			Case Else
				Throw New Exception("Unknown command.")

		End Select

		setDataSourceAndBind()
		DayPilotScheduler1.Update()
	End Sub

	Private Function IsTodayInRange() As Boolean
		If Date.Today >= DayPilotScheduler1.StartDate AndAlso Date.Today < DayPilotScheduler1.EndDate Then
			Return True
		End If
		Return False
	End Function

	Protected Sub DayPilotScheduler1_EventClick(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventClickEventArgs)
		setDataSourceAndBind()
		DayPilotScheduler1.Update(String.Format("Event {0} clicked.", e.Id))

	End Sub
	Protected Sub DayPilotScheduler1_TimeRangeMenuClick(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.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"
			dr("column") = e.ResourceId

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

			setDataSourceAndBind()
			DayPilotScheduler1.Update()
		End If
	End Sub


	''' <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("Scheduler") Is Nothing Then
			Session("Scheduler") = DataGeneratorScheduler.GetData()
		End If
		table = DirectCast(Session("Scheduler"), DataTable)
	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)
		End If
		'throw new Exception(select);

		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

End Class
