﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime.Host;

namespace Host
{
    public class Program
    {
        static void Main(string[] args)
        {
            AppDomain hostDomain = AppDomain.CreateDomain("OrleansHost", null, new AppDomainSetup
            {
                AppDomainInitializer = InitSilo,
                AppDomainInitializerArguments = args,
            });

            Console.WriteLine("Orleans Silo is running.\nPress Enter to terminate...");
            while (true)
            {
                Thread.Sleep(1000 * 60);
                SharpServer.Config.ConfigMetaData.LoadAllConfig();
            }

            hostDomain.DoCallBack(ShutdownSilo);
        }

        static void InitSilo(string[] args)
        {
            siloHost = new SiloHost(System.Net.Dns.GetHostName());
            siloHost.ConfigFileName = "OrleansConfiguration.xml";
            siloHost.InitializeOrleansSilo();
            var started = siloHost.StartOrleansSilo();
            if (!started)
            {
                Console.Error.WriteLine("Failed to initialize Orleans silo");
            }

            SharpServer.SDK.Profile.Enbale = HostSettings.EnableProfile;
            SharpServer.SDK.LoggerProvider.InitLogger(HostSettings.LogPrefix, HostSettings.LogLevel);
            SharpServer.Config.ConfigMetaData.InitConfigPath(HostSettings.ConfigPath);
            SharpServer.Config.ConfigMetaData.LoadAllConfig();
            SharpServer.Record.CassandraClient.InitClient(HostSettings.CassandraHost);
        }

        static void ShutdownSilo()
        {
            if (siloHost != null)
            {
                siloHost.Dispose();
                GC.SuppressFinalize(siloHost);
                siloHost = null;
            }
        }

        static SiloHost siloHost;
    }
}