Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Ink
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Windows.Data
#If SILVERLIGHT Then
Imports C1.Silverlight.FlexGrid
#Else
Imports C1.WPF.FlexGrid
#End If

Namespace MainTestApplication
	' cell factory used to create iTunes cells
	Public Class MusicCellFactory
		Inherits CellFactory
		Private Shared _emptyThickness As New Thickness(0)
		Public _ratings As New List(Of RatingCell)()

		' bind a cell to a range
		Public Overrides Sub CreateCellContent(ByVal grid As C1FlexGrid, ByVal bdr As Border, ByVal range As CellRange)
			' get row/col
			Dim row = grid.Rows(range.Row)
			Dim col = grid.Columns(range.Column)
			Dim gr = TryCast(row, GroupRow)

			' no border for group rows
			If gr IsNot Nothing Then
				bdr.BorderThickness = _emptyThickness
			End If

			' bind first cell in each group row to collapse/expand
			If gr IsNot Nothing AndAlso range.Column = 0 Then
				BindGroupRowCell(grid, bdr, range)
				Return
			End If

			' bind regular data cells
			Select Case col.ColumnName
				' show names with images
				Case "Name"
					bdr.Child = New SongCell(row)
					Return

				' show ratings with stars
				Case "Rating"
					Dim song = TryCast(row.DataItem, Song)
					If song IsNot Nothing Then
						Dim cell = New RatingCell()
						cell.SetBinding(RatingCell.RatingProperty, col.Binding)
						bdr.Child = cell
					End If
					Return
			End Select

			' default binding
			MyBase.CreateCellContent(grid, bdr, range)
		End Sub

		' bind a cell to a group row
		Private Sub BindGroupRowCell(ByVal grid As C1FlexGrid, ByVal bdr As Border, ByVal range As CellRange)
			' get row, group row
			Dim row = grid.Rows(range.Row)
			Dim gr = TryCast(row, GroupRow)

			' show group caption/image on first column
			If range.Column = 0 Then
				' build a custom data item if necessary
				If gr.DataItem Is Nothing Then
					gr.DataItem = BuildGroupDataItem(gr)
				End If

				' get type of cell we need
				Dim cellType As Type = If(gr.Level = 0, GetType(ArtistCell), GetType(AlbumCell))

				' create the cell
				bdr.Child = If(gr.Level = 0, CType(New ArtistCell(row), ImageCell), CType(New AlbumCell(row), ImageCell))
			End If
		End Sub

		' build a song to represent a group
		' the GetChildDataItems method returns all songs that belong
		' to this node, and the LINQ statement below calculates the total 
		' size, length, and average rating for the album/artist.
		Private Function BuildGroupDataItem(ByVal gr As GroupRow) As Song
			Dim gs = gr.GetDataItems().OfType(Of Song)()
			Return New Song() With {.Name = gr.Group.Name.ToString(), .Size = CLng(Fix(gs.Sum(Function(s) s.Size))), .Duration = CLng(Fix(gs.Sum(Function(s) s.Duration))), .Rating = CInt(Fix(gs.Average(Function(s) s.Rating) + 0.5))}
		End Function
	End Class
End Namespace
