using Common;
using CustomMigrationHistory.Context;
using CustomMigrationHistory.Model;
using System;
using System.Collections.Generic;

namespace CustomMigrationHistory
{
    /// <summary>
    /// This program demonstrates Connection Resiliency feature, introduced in Entity Framework 6
    /// Before running this application please ensure followings are done
    /// 1. Connection string is updated with correct connection details in app.config
    /// Note: This application will always clean the database before running. 
    ///       It will delete following three tables from the database
    ///     - "Employees"
    ///     - "__MigrationHistory"
    ///     - "DbOperations" (Customized "__MigrationHitory" table)
    /// </summary>
    class Program
    {
        private static List<string> _TableNames = new List<string> { "Employees", "__MigrationHistory", "DbOperations" };

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Cleaning up Database before use.\n");
                CommonUtility.CleanUpDB(_TableNames, DbObjectType.Table);
                Console.WriteLine("Database cleaning completed.\n");

                using (var db = new PSQLDbContext())
                {
                    //Database Command Logging
                    db.Database.Log = Console.Write;
                    
                    // Creating data for Employee
                    Console.WriteLine("Creating an Employee object.\n");
                    Employee King = new Employee { EmpName = "King", Designation = "PRESIDENT", Salary = 5000 };
                    Console.WriteLine("Created an Employee object.\n");

                    // Add objects to context
                    Console.WriteLine("Adding Employee object to database context.\n");
                    Console.WriteLine("Now DDL for Customized Migration History should appear.\n");
                    db.Employees.Add(King);
                    Console.WriteLine("Added Employee object to database context.\n");

                    // Save changes to database
                    // This will create Employees table
                    // will add Employee record created above
                    Console.WriteLine("Saving object in context to database. It may take some time. Please wait...\n");
                    db.SaveChanges();
                    Console.WriteLine("Saved record successfully to database.\n");

                }
            }
            catch (Exception ex)
            {
                CommonUtility.ProcessExceptionMessage(ex);
            }
            finally
            {
                Console.Write("Press any Key to continue:");
                Console.ReadKey(true);
            }
        }
    }
}
