Imports DataAccess
Imports Model
Imports Telerik.OpenAccess
Imports System.Linq

Public Class ContactBO
    Public Shared Function GetContactGroups() As ObjectContainer.ChangeSet
        Return ContainerManager.LoadChangeSet(Of ContactGroup)()
    End Function

    Public Shared Function GetContacts() As ObjectContainer.ChangeSet
        Return ContainerManager.LoadChangeSet(Of Contact)()
    End Function

    Public Shared Function SaveContacts( _
    ByVal changeSet As ObjectContainer.ChangeSet) _
    As ObjectContainer.ChangeSet
        Dim contacts As IQueryable(Of Contact) = _
      ContainerManager.LoadQueryable(Of Contact)(changeSet)

        Dim invalidContacts As IQueryable(Of Contact) = _
      InvalidPhoneContacts(contacts)
        If invalidContacts.Count() > 0 Then
            Dim message As String = "Invalid phone numbers"

            Dim businessException As New ContactException(message, _
         invalidContacts.ToList())
            Throw businessException
        End If

        Return ContainerManager.SaveChangeSet(changeSet)
    End Function

    Private Shared Function InvalidPhoneContacts( _
ByVal queryable As IQueryable(Of Contact)) _
As IQueryable(Of Contact)
        Dim regexPhone As New System.Text.RegularExpressions.Regex( _
      My.Settings.Default.RegExPhone)

        Dim invalidContacts As IQueryable(Of Contact) = _
           From q In queryable _
           Where regexPhone.Matches(q.Phone).Count = 0 _
           Select q

        Return invalidContacts
    End Function
End Class
