using System.Linq;
using DataAccess;
using Model;
using Telerik.OpenAccess;

namespace Business
{
  public class ContactBO
  {
    public static ObjectContainer.ChangeSet GetContactGroups()
    {
      return ContainerManager.LoadChangeSet<ContactGroup>();
    }

    public static ObjectContainer.ChangeSet GetContacts()
    {
      return ContainerManager.LoadChangeSet<Contact>();
    }

    public static ObjectContainer.ChangeSet SaveContacts(
      ObjectContainer.ChangeSet changeSet)
    {
      IQueryable<Contact> contacts =
        ContainerManager.LoadQueryable<Contact>(changeSet);

      IQueryable<Contact> invalidContacts = InvalidPhoneContacts(contacts);
      if (invalidContacts.Count() > 0)
      {
        string message = "Invalid phone numbers";

        ContactException businessException =
          new ContactException(message, invalidContacts.ToList<Contact>());
        throw businessException;
      }

      return ContainerManager.SaveChangeSet(changeSet);
    }

    private static IQueryable<Contact> InvalidPhoneContacts(IQueryable<Contact> queryable)
    {
      System.Text.RegularExpressions.Regex regexPhone =
        new System.Text.RegularExpressions.Regex(
          Properties.Settings.Default.RegExPhone);

      IQueryable<Contact> invalidContacts =
          from q
            in queryable
          where regexPhone.Matches(q.Phone).Count == 0
          select q;

      return invalidContacts;
    }

  }
}

