Imports C1.Silverlight.FlexGrid
Imports C1.Silverlight.Excel

Imports System.Globalization
Imports System.Windows

Namespace ExcelExport

    ''' <summary>
    ''' Grid row that can be edited, used as a tree node, maintains a 
    ''' collection of cell styles associated with each column
    ''' </summary>
    Public Class ExcelRow
        Inherits GroupRow
        ' ** fields
        Private _cellStyles As Dictionary(Of Column, CellStyle)

        Private Const DEFAULT_FORMAT As String = "#,##0.######" ' set default precision to 6 digits

        ' ** ctor
        Public Sub New(ByVal styleRow As ExcelRow)
            IsReadOnly = False
            If styleRow IsNot Nothing AndAlso styleRow.Grid IsNot Nothing Then
                For Each c In styleRow.Grid.Columns
                    Dim cs = styleRow.GetCellStyle(c)
                    If cs IsNot Nothing Then
                        Me.SetCellStyle(c, cs.Clone())
                    End If
                Next c
            End If
        End Sub
        Public Sub New()
            Me.New(Nothing)
        End Sub

        ' ** object model

        ''' <summary>
        ''' Overridden to apply formatting when getting data.
        ''' </summary>
        Public Overrides Function GetDataFormatted(ByVal col As Column) As String
            ' get data as usual
            Dim data = GetDataRaw(col)

            ' apply format
            Dim ifmt = TryCast(data, IFormattable)
            If ifmt IsNot Nothing Then
                ' get cell format
                Dim s = TryCast(GetCellStyle(col), ExcelCellStyle)
                Dim fmt = If(s IsNot Nothing AndAlso (Not String.IsNullOrEmpty(s.Format)), s.Format, DEFAULT_FORMAT)
                data = ifmt.ToString(fmt, CultureInfo.CurrentUICulture)
            End If

            ' done
            Return If(data IsNot Nothing, data.ToString(), String.Empty)
        End Function

        ' ** object model

        ''' <summary>
        ''' Applies a style to a cell in this row.
        ''' </summary>
        Public Sub SetCellStyle(ByVal col As Column, ByVal style As CellStyle)
            If style IsNot GetCellStyle(col) Then
                If _cellStyles Is Nothing Then
                    _cellStyles = New Dictionary(Of Column, CellStyle)()
                End If
                _cellStyles(col) = style
                If Grid IsNot Nothing Then
                    Grid.Invalidate(New CellRange(Me.Index, col.Index))
                End If
            End If
        End Sub
        ''' <summary>
        ''' Gets the style applied to a cell in this row.
        ''' </summary>
        Public Function GetCellStyle(ByVal col As Column) As CellStyle
            Dim s As CellStyle = Nothing
            If _cellStyles IsNot Nothing Then
                _cellStyles.TryGetValue(col, s)
            End If
            Return s
        End Function

    End Class
End Namespace
