Imports System
Imports System.Collections
Imports System.Data
Imports System.Linq
Imports System.Web.Script.Services
Imports System.Web.Services
Imports Data
Imports DayPilot.Utils
Imports DayPilot.Web.Ui.Data
Imports DayPilot.Web.Ui.Enums
Imports DayPilot.Web.Ui.Events
Imports DayPilot.Web.Ui.Events.Calendar
Imports Newtonsoft.Json
Imports BeforeTimeHeaderRenderEventArgs = DayPilot.Web.Ui.Events.Calendar.BeforeTimeHeaderRenderEventArgs
Imports CommandEventArgs = DayPilot.Web.Ui.Events.CommandEventArgs

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

	Private blocks As DataTable

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
		blocks = (New DataManager()).GetBlocks()

		If Not IsPostBack Then
			DayPilotCalendar1.StartDate = Week.FirstWorkingDayOfWeek(DayPilotNavigator1.SelectionStart)
			DayPilotCalendar1.Days = 5

			DayPilotCalendar1.DataSource = (New DataManager()).GetAssignments(DayPilotCalendar1)
			DayPilotCalendar1.DataBind()
		End If
	End Sub

	Protected Sub DayPilotCalendar1_OnBeforeTimeHeaderRender(ByVal ea As BeforeTimeHeaderRenderEventArgs)
'NOTE: The variable id was renamed since Visual Basic does not handle local variables named the same as class members well:
		Dim id_Renamed As Integer = ea.Start.Hours
		Dim r As DataRow = FindBlock(id_Renamed)

		If r IsNot Nothing Then
			ea.InnerHTML = String.Format("Block {0}<br/>{1}<br/>{2}", id_Renamed, TimeFormatter.GetHourMinutes(DirectCast(r("BlockStart"), Date), DayPilotCalendar1.TimeFormat), TimeFormatter.GetHourMinutes(DirectCast(r("BlockEnd"), Date), DayPilotCalendar1.TimeFormat))
		Else
			ea.InnerHTML = "Unknown Block."
		End If

		ea.Areas.Add((New Area()).Width(15).Top(0).Bottom(0).Right(0).CssClass("resource_action_menu").Html("<div><div></div></div>").JavaScript("editBlock(e);"))
	End Sub


	Private Function FindBlock(ByVal i As Integer) As DataRow
		Return blocks.Rows.Cast(Of DataRow)().FirstOrDefault(Function(dr) Convert.ToInt32(dr("BlockId")) = i)
	End Function

	Protected Sub DayPilotCalendar1_OnCommand(ByVal sender As Object, ByVal e As CommandEventArgs)
		Select Case e.Command
			Case "navigate"
				DayPilotCalendar1.StartDate = Week.FirstWorkingDayOfWeek(CDate(e.Data("start")))
				DayPilotCalendar1.Update()
				LoadEvents()

			Case "refresh"
				LoadEvents()

				If e.Data IsNot Nothing AndAlso e.Data("message") IsNot Nothing Then
					DayPilotCalendar1.UpdateWithMessage(CStr(e.Data("message")))
				Else
					DayPilotCalendar1.UpdateWithMessage("Updated.")
				End If

		End Select
	End Sub

	Private Sub LoadEvents()
		DayPilotCalendar1.DataSource = (New DataManager()).GetAssignments(DayPilotCalendar1)
		DayPilotCalendar1.DataBind()
	End Sub

	Protected Sub DayPilotCalendar1_EventMove(ByVal sender As Object, ByVal e As EventMoveEventArgs)
		Call (New DataManager()).MoveAssignment(Convert.ToInt32(e.Value), e.NewStart, e.NewEnd)
		DayPilotCalendar1.DataSource = (New DataManager()).GetAssignments(DayPilotCalendar1)
		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update()
	End Sub

	Protected Sub DayPilotCalendar1_EventResize(ByVal sender As Object, ByVal e As EventResizeEventArgs)
		Call (New DataManager()).MoveAssignment(Convert.ToInt32(e.Value), e.NewStart, e.NewEnd)
		DayPilotCalendar1.DataSource = (New DataManager()).GetAssignments(DayPilotCalendar1)
		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update()
	End Sub

	Protected Sub DayPilotCalendar1_BeforeEventRender(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.Calendar.BeforeEventRenderEventArgs)
		Dim color As String = CStr(e.DataItem("AssignmentColor"))
		If Not String.IsNullOrEmpty(color) AndAlso color <> "default" Then
			e.BackgroundColor = color
			e.BorderColor = color
			e.FontColor = "#ffffff"
		End If
	End Sub


	<WebMethod, ScriptMethod(UseHttpGet := True)>
	Public Shared Function GetBlocks() As String
		' int id = Convert.ToInt32(idStr);

		Dim blocks As DataTable = (New DataManager()).GetBlocks()

'NOTE: The variable items was renamed since Visual Basic does not handle local variables named the same as class members well:
		Dim items_Renamed As New ArrayList()

		For Each r As DataRow In blocks.Rows
'NOTE: The variable id was renamed since Visual Basic does not handle local variables named the same as class members well:
			Dim id_Renamed As Integer = Convert.ToInt32(r("BlockId"))
			Dim start As Date = DirectCast(r("BlockStart"), Date)
			Dim [end] As Date = DirectCast(r("BlockEnd"), Date)
			Dim name As String = String.Format("Block {0} ({1} - {2})", id_Renamed, TimeFormatter.GetHourMinutes(start, TimeFormat.Auto), TimeFormatter.GetHourMinutes([end], TimeFormat.Auto))
			Dim item As New Hashtable()
			item("name") = name
			item("id") = id_Renamed
			items_Renamed.Add(item)
		Next r


		Dim result As New Hashtable()
		result("data") = items_Renamed
		Return JsonConvert.SerializeObject(result)
	End Function

	<WebMethod, ScriptMethod(ResponseFormat := ResponseFormat.Json)>
	Public Shared Function Create(ByVal day As Date, ByVal start As Integer, ByVal duration As Integer, ByVal description As String, ByVal color As String) As String
		Dim totalBlocks As Integer = 8
		duration = If(start + duration > totalBlocks, totalBlocks - start, duration) ' make sure it's within the visible range

		day = day.Date
		Dim startDate As Date = day.Add(TimetableManager.MapBlock(start))
		Dim endDate As Date = startDate.Add(TimetableManager.MapBlock(duration))

		Call (New DataManager()).CreateAssignment(startDate, endDate, description, color)

		Dim result As New Hashtable()
		result("status") = "OK"
		result("message") = "Created"
		Return JsonConvert.SerializeObject(result)
	End Function


	<WebMethod, ScriptMethod(UseHttpGet := True)>
	Public Shared Function GetAssignment(ByVal id As Integer) As String
		Dim dr As DataRow = (New DataManager()).GetAssignment(id)
		Dim result As New Hashtable()

		Dim start As Date = TimetableManager.UnmapEventStart(DirectCast(dr("AssignmentStart"), Date))
		Dim [end] As Date = TimetableManager.UnmapEventEnd(DirectCast(dr("AssignmentEnd"), Date))

		result("id") = id
		result("start") = start
		result("end") = [end]
		result("description") = Convert.ToString(dr("AssignmentNote"))
		result("color") = DirectCast(dr("AssignmentColor"), String)

		Return JsonConvert.SerializeObject(result)
	End Function


	<WebMethod, ScriptMethod(ResponseFormat := ResponseFormat.Json)>
	Public Shared Function Update(ByVal id As Integer, ByVal description As String, ByVal color As String) As String
		Call (New DataManager()).UpdateAssignmentNote(id, description, color)

		Dim result As New Hashtable()
		result("status") = "OK"
		result("message") = "Updated"
		Return JsonConvert.SerializeObject(result)
	End Function

	<WebMethod, ScriptMethod(UseHttpGet := True)>
	Public Shared Function GetBlock(ByVal id As Integer) As String
		Dim dr As DataRow = (New DataManager()).GetBlock(id)
		Dim result As New Hashtable()

		result("id") = id
		result("startMinutes") = DirectCast(dr("BlockStart"), Date).TimeOfDay.TotalMinutes
		result("endMinutes") = DirectCast(dr("BlockEnd"), Date).TimeOfDay.TotalMinutes

		Return JsonConvert.SerializeObject(result)
	End Function


	<WebMethod, ScriptMethod(ResponseFormat := ResponseFormat.Json)>
	Public Shared Function UpdateBlock(ByVal id As Integer, ByVal startMinutes As Integer, ByVal endMinutes As Integer) As String
		Dim start As TimeSpan = TimeSpan.FromMinutes(startMinutes)
		Dim [end] As TimeSpan = TimeSpan.FromMinutes(endMinutes)

		Dim block As DataRow = (New DataManager()).GetBlock(id)
		If block Is Nothing Then
			Call (New DataManager()).InsertBlock(id, start, [end])
		Else
			Call (New DataManager()).UpdateBlock(id, start, [end])
		End If

		Dim result As New Hashtable()
		result("status") = "OK"
		result("message") = "Updated"
		Return JsonConvert.SerializeObject(result)
	End Function

	Protected Sub DayPilotCalendar1_OnEventDelete(ByVal sender As Object, ByVal e As EventDeleteEventArgs)
		Call (New DataManager()).DeleteAssignment(Convert.ToInt32(e.Id))
		DayPilotCalendar1.DataSource = (New DataManager()).GetAssignments(DayPilotCalendar1)
		DayPilotCalendar1.DataBind()
		DayPilotCalendar1.Update()
	End Sub
End Class