Public Class PaintingObjectListLayering


    Public ReadOnly Property ObjectList As PaintingObjectList
    Public ReadOnly Property Conditions As New Dictionary(Of Integer, Func(Of PaintingObject, Boolean))

    ''' <summary>
    ''' Get the order function will checkout the conditions.
    ''' </summary>
    ''' <returns>Returns true, if conditions are aviable, otherwise false.</returns>
    Public ReadOnly Property EnableConditions As Boolean
        Get
            Return Conditions.Any
        End Get
    End Property

    ''' <summary>
    ''' Create a new instance of object list layer managing.
    ''' </summary>
    ''' <param name="list"></param>
    Public Sub New(list As PaintingObjectList)
        ObjectList = list
    End Sub

    ''' <summary>
    ''' Order all objects using the conditions. If no conditions are setted, this method will do nothing.
    ''' </summary>
    Public Sub OrderAll()
        If EnableConditions Then
            OrderAllPrivate()
        End If
    End Sub

    Private Sub OrderAllPrivate()
        Dim list As PaintingObjectList = ObjectList
        Dim listOld As List(Of PaintingObject) = list.ToList
        Dim toRemove As New List(Of PaintingObject)

        'Disable raising events
        ObjectList.EnableRaisingEvents = False

        'Clear list
        list.Clear()

        'Add ordered
        For Each kvp In Conditions.OrderBy(Function(n) n.Key)
            Dim func = kvp.Value

            For Each obj As PaintingObject In listOld
                If func(obj) Then
                    'Add to list
                    list.Add(obj)

                    'Add to remove
                    toRemove.Add(obj)
                End If
            Next

            'Remove remembered objects
            For Each obj As PaintingObject In toRemove
                listOld.Remove(obj)
            Next
            toRemove.Clear()
        Next

        'Enable raising events
        ObjectList.EnableRaisingEvents = True

        'Refresh
        ObjectList.MyParent?.Refresh()
    End Sub

End Class
