Option Strict On
Option Explicit On

Imports System
Imports System.Globalization

Namespace Nexamas.UI.PropertyGrid

    Friend NotInheritable Class MASPropertyGridText
        Private Sub New()
        End Sub

        Friend Shared Function Normalize(value As String, fallback As String) As String
            Dim result As String = If(value, String.Empty).Trim()
            If result.Length = 0 Then result = If(fallback, String.Empty).Trim()
            Return result
        End Function

        Friend Shared Function FormatValue(value As Object) As String
            If value Is Nothing Then Return String.Empty
            If TypeOf value Is Boolean Then Return CBool(value).ToString(CultureInfo.InvariantCulture)
            If TypeOf value Is IFormattable Then Return DirectCast(value, IFormattable).ToString(Nothing, CultureInfo.InvariantCulture)
            Return Convert.ToString(value, CultureInfo.InvariantCulture)
        End Function

        Friend Shared Function InferKind(valueType As Type, value As Object) As MASPropertyGridValueKind
            Dim effectiveType As Type = Nullable.GetUnderlyingType(valueType)
            If effectiveType Is Nothing Then effectiveType = valueType
            If effectiveType Is Nothing AndAlso value IsNot Nothing Then effectiveType = value.GetType()
            If effectiveType Is Nothing Then Return MASPropertyGridValueKind.Text

            If effectiveType Is GetType(String) Then Return MASPropertyGridValueKind.Text
            If effectiveType Is GetType(Boolean) Then Return MASPropertyGridValueKind.BooleanValue
            If effectiveType.IsEnum Then Return MASPropertyGridValueKind.EnumValue
            If effectiveType Is GetType(DateTime) Then Return MASPropertyGridValueKind.DateTimeText
            If IsNumericType(effectiveType) Then Return MASPropertyGridValueKind.Number
            Return MASPropertyGridValueKind.ObjectText
        End Function

        Friend Shared Function IsNumericType(valueType As Type) As Boolean
            If valueType Is Nothing Then Return False
            Dim effectiveType As Type = Nullable.GetUnderlyingType(valueType)
            If effectiveType Is Nothing Then effectiveType = valueType

            Return effectiveType Is GetType(Byte) OrElse
                   effectiveType Is GetType(SByte) OrElse
                   effectiveType Is GetType(Int16) OrElse
                   effectiveType Is GetType(UInt16) OrElse
                   effectiveType Is GetType(Int32) OrElse
                   effectiveType Is GetType(UInt32) OrElse
                   effectiveType Is GetType(Int64) OrElse
                   effectiveType Is GetType(UInt64) OrElse
                   effectiveType Is GetType(Single) OrElse
                   effectiveType Is GetType(Double) OrElse
                   effectiveType Is GetType(Decimal)
        End Function

    End Class

End Namespace
