using EgtBEAMWALL.DataLayer.DatabaseModels;
using EgtBEAMWALL.DataLayer.Migrations;
using MySql.Data.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.ServiceProcess;

namespace EgtBEAMWALL.DataLayer
{
    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class AdminContext : DbContext
    {
        #region Public Constructors

        [Obsolete("This constructor should never be used directly, and is only needed to generate entityframework stuff. Connection string can be adapted as pleased.")]
        public AdminContext() : base(DbConfig.ADMIN_CONNECTION_STRING)
        {
        }

        public AdminContext(string connectionString) : base(connectionString)
        {
        }

        #endregion Public Constructors

        #region Public Properties

        /// <summary>
        /// User management
        /// </summary>
        public DbSet<UserPriv> UserList { get; set; }

        #endregion Public Properties

        #region Public Methods

        public bool SetUpDbConnectionAndDbConfig()
        {
            try
            {
                String serviceName = getDbServiceName();
                if (serviceName.Equals(""))
                {
                    return false;
                }

                ServiceController service = new ServiceController(serviceName);
                try
                {
                    TimeSpan timeout = TimeSpan.FromSeconds(DbConfig.DATABASE_PROCESS_TIMEOUT);
                    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                }
                catch (Exception)
                {
                    return false;
                }

                //Database.SetInitializer<DatabaseContext>(null);
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
                var migrator = new DbMigrator(new Configuration());

                if (migrator.GetPendingMigrations().Any())
                {
                    // Run migrations and seed.
                    migrator.Update();
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                return false;
            }

            return true;
        }

        #endregion Public Methods

        #region Private Methods

        private static string getDbServiceName()
        {
            ServiceController[] services = ServiceController.GetServices();
            var service = services.FirstOrDefault(s => s.ServiceName == "MariaDB");
            if (service != null)
                return service.DisplayName;

            service = services.FirstOrDefault(s => s.ServiceName == "MySQL");
            if (service != null)
                return service.DisplayName;

            return "";
        }

        #endregion Private Methods
    }
}