Option Strict On
Option Explicit On

Imports System.Collections.Generic

Namespace Nexamas.UI.Virtualization

    ''' <summary>
    ''' Internal lease pool for virtualized visual containers. The pool owns only numeric leases in Phase 2 so it stays UI-neutral;
    ''' future controls can map lease ids to actual visual containers without changing the planning engine. Released lease ids are
    ''' tracked defensively so a consumer bug cannot enqueue the same lease twice and later duplicate a visual container lease.
    ''' </summary>
    Friend NotInheritable Class MASVirtualizationRecyclePool

        Private ReadOnly _availableLeaseIds As Queue(Of Integer)
        Private ReadOnly _availableLeaseIdSet As HashSet(Of Integer)
        Private _nextLeaseId As Integer
        Private _createdLeaseCount As Integer
        Private _reusedLeaseCount As Integer

        Friend Sub New()
            _availableLeaseIds = New Queue(Of Integer)()
            _availableLeaseIdSet = New HashSet(Of Integer)()
            _nextLeaseId = 1
        End Sub

        Friend ReadOnly Property CreatedLeaseCount As Integer
            Get
                Return _createdLeaseCount
            End Get
        End Property

        Friend ReadOnly Property ReusedLeaseCount As Integer
            Get
                Return _reusedLeaseCount
            End Get
        End Property

        Friend ReadOnly Property AvailableLeaseCount As Integer
            Get
                Return _availableLeaseIds.Count
            End Get
        End Property

        Friend Function Acquire(ByRef acquiredFromRecyclePool As Boolean) As Integer
            If _availableLeaseIds.Count > 0 Then
                acquiredFromRecyclePool = True
                _reusedLeaseCount += 1
                Dim leaseId = _availableLeaseIds.Dequeue()
                _availableLeaseIdSet.Remove(leaseId)
                Return leaseId
            End If

            acquiredFromRecyclePool = False
            Dim id = _nextLeaseId
            _nextLeaseId += 1
            _createdLeaseCount += 1
            Return id
        End Function

        Friend Sub Release(leaseId As Integer)
            If leaseId <= 0 Then
                Return
            End If

            If _availableLeaseIdSet.Contains(leaseId) Then
                Return
            End If

            _availableLeaseIdSet.Add(leaseId)
            _availableLeaseIds.Enqueue(leaseId)
        End Sub

    End Class

End Namespace
