using System;
using System.Collections.Generic;
using System.Linq;
using VSMMvcTDD.Entities;

namespace VSMMvcTDD.Services
{
    public class ContactService : IContactService
    {
        private readonly ContactContext _contactContext;

        public ContactService(ContactContext contactContext)
        {
            _contactContext = contactContext;
        }

        public IQueryable<Contact> GetAllContacts()
        {
            return _contactContext.Contacts;
        }

        public int AddContact(Contact contact)
        {
            _contactContext.Contacts.Add(contact);
            _contactContext.SaveChanges();
            return contact.Id;
        }

        public Contact GetContact(int id)
        {
            return _contactContext.Contacts.SingleOrDefault(c => c.Id == id);
        }

        public void EditContact(Contact contact)
        {
            var existing = GetContact(contact.Id);
            existing.FirstName = contact.FirstName;
            existing.LastName = contact.LastName;
            existing.Email = contact.Email;
            _contactContext.SaveChanges();
        }

        public void DeleteContact(int id)
        {
            var existing = GetContact(id);
            _contactContext.Contacts.Remove(existing);
            _contactContext.SaveChanges();
        }
    }
}