using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using IdeaBladeMVC.Data;

namespace IdeaBladeMVC.Models {
  public class CustomerRepository : ICustomerRepository {
    IdeaBladeMVCContext context = new IdeaBladeMVCContext();

    public IEnumerable<Customer> GetAllCustomers(params Expression<Func<Customer, object>>[] includeProperties) {
      IQueryable<Customer> query = context.Customers;
      foreach (var includeProperty in includeProperties) {
        query = query.Include(includeProperty);
      }
      return query.ToList();
    }

    public Customer GetById(Guid id) {
      return context.Customers.FirstOrDefault(c => c.CustomerID == id);
    }

    public void InsertOrUpdate(Customer customer) {
      if (customer.CustomerID == default(Guid)) {
        customer.CustomerID = Guid.NewGuid();
        context.AddEntity(customer);
      } else {
        context.AttachEntity(customer);
        customer.EntityAspect.SetModified();
      }
    }

    public void Delete(Guid id) {
      var customer = GetById(id);
      if (customer != null)
        customer.EntityAspect.Delete();
    }

    public void Save() {
      var added = context.FindEntities(IdeaBlade.EntityModel.EntityState.Added);
      var modified = context.FindEntities(IdeaBlade.EntityModel.EntityState.Modified);
      context.SaveChanges();
    }
  }

  public interface ICustomerRepository {
    IEnumerable<Customer> GetAllCustomers(params Expression<Func<Customer, object>>[] includeProperties);
    Customer GetById(Guid id);
    void InsertOrUpdate(Customer customer);
    void Delete(Guid id);
    void Save();
  }
}