using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
using Rainbow.Models;

namespace Rainbow.Data
{
    public class RainbowContext : IdentityDbContext<ApplicationUser>
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<Rainbow.Models.RainbowContext>());

        public RainbowContext() : base("name=RainbowContext")
        {
        }

        public DbSet<Domain> Domains { get; set; }

        public DbSet<Customer> Customers { get; set; }

        public DbSet<Project> Projects { get; set; }

        public DbSet<Registrar> Registrars { get; set; }

        public DbSet<HostingAccount> HostingAccounts { get; set; }

        public DbSet<Server> Servers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new Configuration.CustomerConfiguration());
            modelBuilder.Configurations.Add(new Configuration.DomainConfiguration());

            base.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges()
        {
            // update created and last modified dates
            foreach (var entry in ChangeTracker.Entries().Where(e => e.Entity is IAuditInfo && (e.State == EntityState.Added || e.State == EntityState.Modified)))
            {
                var info = entry.Entity as IAuditInfo;
                if (info != null)
                {
                    if (entry.State == EntityState.Added)
                    {
                        info.Created = DateTime.Now;
                        if (HttpContext.Current != null)
                        {
                            info.CreatedBy = HttpContext.Current.User.Identity.Name;
                        }
                    }
                    info.LastModified = DateTime.Now;
                    if (HttpContext.Current != null)
                    {
                        info.LastModifiedBy = HttpContext.Current.User.Identity.Name;
                    }
                }
            }
            return base.SaveChanges();
        }

        public System.Data.Entity.DbSet<Rainbow.Models.TicketResponse> TicketResponses { get; set; }

        public System.Data.Entity.DbSet<Rainbow.Models.Ticket> Tickets { get; set; }
    }
}