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

namespace ConnectionResiliency
{
    /// <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 cleans the database before running. 
    ///     It deletes following two tables from the database
    ///     - "Employees"
    ///     - "__MigrationHistory"
    /// </summary>
    class Program
    {
        private static List<string> _TableNames = new List<string> { "Employees", "__MigrationHistory" };

        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())
                {
                    // 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");
                    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");
                    Console.WriteLine("Expecting an Exception here saying maximum number or retries(5) has exceeded.\n");
                    db.SaveChanges();
                    Console.WriteLine("Saved record successfully to database. Connection Resiliency failed.\n");

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