Option Strict On
Option Explicit On

Namespace Nexamas.UI.DataBinding

    ''' <summary>
    ''' Stable field definition for building a compact pivot projection from an
    ''' IMASItemsSource snapshot. The definition names one row field, one column
    ''' field, one optional numeric value field, and the aggregate to apply.
    ''' </summary>
    Friend NotInheritable Class MASPivotSourceDefinition

        Friend Sub New(rowField As String,
                       columnField As String,
                       valueField As String,
                       Optional aggregateKind As MASPivotAggregateKind = MASPivotAggregateKind.Sum)
            Me.RowField = NormalizeFieldName(rowField)
            Me.ColumnField = NormalizeFieldName(columnField)
            Me.ValueField = NormalizeFieldName(valueField)
            Me.AggregateKind = aggregateKind
        End Sub

        Friend ReadOnly Property RowField As String
        Friend ReadOnly Property ColumnField As String
        Friend ReadOnly Property ValueField As String
        Friend ReadOnly Property AggregateKind As MASPivotAggregateKind

        Friend ReadOnly Property IsValid As Boolean
            Get
                If RowField.Length = 0 Then Return False
                If ColumnField.Length = 0 Then Return False
                If AggregateKind <> MASPivotAggregateKind.Count AndAlso ValueField.Length = 0 Then Return False
                Return True
            End Get
        End Property

        Friend Shared Function Create(rowField As String,
                                      columnField As String,
                                      valueField As String,
                                      Optional aggregateKind As MASPivotAggregateKind = MASPivotAggregateKind.Sum) As MASPivotSourceDefinition
            Return New MASPivotSourceDefinition(rowField, columnField, valueField, aggregateKind)
        End Function

        Private Shared Function NormalizeFieldName(value As String) As String
            Dim normalized As String = If(value, String.Empty).Trim()
            normalized = normalized.Replace(ControlChars.Cr, " "c).Replace(ControlChars.Lf, " "c).Replace(ControlChars.Tab, " "c)
            While normalized.Contains("  ")
                normalized = normalized.Replace("  ", " ")
            End While
            If normalized.Length > 96 Then normalized = normalized.Substring(0, 96)
            Return normalized
        End Function

    End Class

End Namespace
