using Microsoft.EntityFrameworkCore;
using pavesys_iRAP.DTO;
using pavesys_iRAP.DTO.Import;
using pavesys_iRAP.Helper;
using Serilog;
using System;
using System.Diagnostics;
using System.Text;

namespace pavesys_iRAP.Business
{
    public class PersistenceContext : DbContext
    {
        public DbSet<Coding> Codings { get; set; }
        public DbSet<CodingImage> CodingImages { get; set; }
        public DbSet<Project> Projects { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<ImageImport> ImagesImport { get; set; }

        protected override void OnConfiguring(
            DbContextOptionsBuilder optionsBuilder)
        {
            var dbConfig = ConfigManager.getActiveDbProfile();
            optionsBuilder.UseSqlServer($"Server=.\\SQLEXPRESS;Database={dbConfig.DatabaseName};Integrated Security=false;Encrypt=false;User Id={dbConfig.DatabaseUser};Password={dbConfig.DatabasePassword};");
            optionsBuilder.EnableDetailedErrors();
            optionsBuilder.EnableSensitiveDataLogging();
            
            optionsBuilder.UseLazyLoadingProxies();

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("dbo");
            // modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<CodingImage>()
                  .HasKey(m => new { m.CodingId, m.Sequence, m.Type });

            modelBuilder.Entity<ImageImport>()
                  .HasKey(m => new { m.SeqImport, m.CameraType });
            modelBuilder.Entity<Coding>().Property(coding => coding.Latitude).HasPrecision(12, 8);
            modelBuilder.Entity<Coding>().Property(coding => coding.Longitude).HasPrecision(12, 8);
            modelBuilder.Entity<Project>().Property(proj => proj.ViaSeguraLabeled).IsRequired(false);
        }

        public Exception HandleDbUpdateException(DbUpdateException dbu)
        {
            var builder = new StringBuilder("A DbUpdateException was caught while saving changes. ");

            try
            {
                foreach (var result in dbu.Entries)
                {
                    builder.AppendFormat("Type: {0} was part of the problem. ", result.Entity.GetType().Name);
                }
            }
            catch (Exception e)
            {
                builder.Append("Error parsing DbUpdateException: " + e.ToString());
            }

            string message = builder.ToString();
            return new Exception(message, dbu);
        }
    }
}
