using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
using Interfaces;
using Microsoft.Owin.Hosting;

namespace WindowsDataCenter
{
    public partial class DataCenterService: ServiceBase
    {
        public DataCenterService()
        {
            InitializeComponent();
        }

        private IDisposable _webApp;
        private bool _stopMainWorkerThread;
        private Thread _mainWorkerThread;
        private ILogger _logger;

        public void Start()
        {
            OnStart(new string[] {});
        }

        public void Stop()
        {
            OnStop();
        }

        protected override void OnStart(string[] args)
        {
            var configPath = string.Concat(System.Reflection.Assembly.GetEntryAssembly().Location, ".config");
            //var configsDir = new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "configs")).LocalPath;
            //var exeName = Assembly.GetEntryAssembly().ManifestModule.ScopeName;
            //var appConfigPath = Path.Combine(configsDir, string.Format("{0}.config", exeName));
            //AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", appConfigPath);
            //var val = ConfigurationManager.AppSettings["TEST"];

            //Initialise the Ninject system.
            var ninjectInstance = NinjectHelper.GetInstance();
            _logger = NinjectHelper.GetInstance().Get<ILogger>();
            _logger.Trace("Starting Data Center Service");
            
            _logger.Trace("Monitoring App.config for changes");
            _mainWorkerThread = new Thread(MainWorkerThread)
            {
                IsBackground = false,
                Name = "DATACENTER SELF HOST MAIN THREAD"
            };

            var endpointPort = ConfigurationManager.AppSettings["WebsiteHttpPort"] ?? "8800";
            try
            {
                var endpoint = string.Format("http://*:{0}", endpointPort);
                _webApp = WebApp.Start<StartOwin>(endpoint);
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex);
            }
        }

        protected override void OnStop()
        {
            _logger.Trace("Stopping Data Center Service");

            _webApp.Dispose();
            _logger.Trace("Stopped WebApi");
            
            _stopMainWorkerThread = true;
            if (_mainWorkerThread != null && _mainWorkerThread.IsAlive)
            {
                _mainWorkerThread.Join(2000);
                if (_mainWorkerThread.IsAlive)
                {
                    _mainWorkerThread.Interrupt();
                }
            }
            _logger.Trace("Exiting..");
        }

        private void MainWorkerThread()
        {
            while (!_stopMainWorkerThread)
            {
                Thread.Sleep(2000);
            }
        }
    }
}
