using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Text;

using Medivators.Common;
using Medivators.Common.Enums;
using Medivators.Common.Logging;
using Medivators.Common.Settings;
using Medivators.Parser;
using Medivators.SerialDevices;

namespace Medivators.Listener
{
	public class ListenerServiceHelper
	{
		public void Continue()
		{
			try
			{
				Log.GetInstance().WriteLog(LogEntryType.Normal,
										   "ListenerService Continued",
										   EventLogEntryType.Information);

				//	Start cache and parser
				CacheManager.GetInstance().Start();
				ParseDispatcher.GetInstance().Start();
			}
			catch (Exception ex)
			{
				ErrorHandler.GetInstance().LogException("ListenerService.OnContinue error:", ex);
			}
		}

		public void Pause()
		{
			try
			{
				Log.GetInstance().WriteLog(LogEntryType.Normal,
										  "ListenerService Paused",
										   EventLogEntryType.Information);

				//	stop cache and parser
				CacheManager.GetInstance().Stop();
				ParseDispatcher.GetInstance().Stop();
			}
			catch (Exception ex)
			{
				ErrorHandler.GetInstance().LogException("ListenerService.OnPause error:", ex);
			}
		}

		public void Shutdown(ref SerialDeviceCollection Devices)	
		{
			Log.GetInstance().WriteLog(LogEntryType.Normal,
						   "ListenerService Shutting down",
						   EventLogEntryType.Information);
			Devices.Dispose();
			CacheManager.GetInstance().Stop();
			ParseDispatcher.GetInstance().Stop();
		}

		public void Start(ref ILogProvider PrimaryLog, 
						  ref ILogProvider SecondaryLog, 
						  ref SerialDeviceCollection Devices)
		{
			//	start log providers and error handling 
			InitLogProviders(ref PrimaryLog, ref SecondaryLog);
			Log.GetInstance().Provider = PrimaryLog;
			ErrorHandler.GetInstance().Initialize(PrimaryLog, SecondaryLog);
			Log.GetInstance().WriteLog("ListenerService reports Logs and ErrorHandler initialized", EventLogEntryType.Information);

            try
            {
                //	load settings
                TextSettings.GetInstance().Load(Constants.MedivatorsProgramFiles,
                                                Constants.MedivatorsSettingsFile);
                LogSettingNamesAndValues();

                //	initialize devices
                Devices = new SerialDeviceCollection(PrimaryLog);
                Devices.SerialDeviceType = SupportedSerialDevices.DSD201;
                int openedDevices = Devices.LoadDevices();
                Log.GetInstance().WriteLog(string.Format("ListenerService reports {0} devices loaded",
                                                         openedDevices),
                                                         EventLogEntryType.Information);
                
                //	start cache and parser
                CacheManager.GetInstance().Start();
                ParseDispatcher.GetInstance().Start();
            }
            catch (Exception ex)
            {
                ErrorHandler.GetInstance().LogException("ListenerService.OnStart:", ex);
            }
            finally
            {
                TextSettings.GetInstance().Dispose();
            }
		}

		public void Stop(ref SerialDeviceCollection Devices)
		{
			Log.GetInstance().WriteLog(LogEntryType.Normal,
						   "ListenerService Stopped",
						   EventLogEntryType.Information);
			Shutdown(ref Devices);
		}

		#region private helpers

		private void InitLogProviders(ref ILogProvider PrimaryLog,
									  ref ILogProvider SecondaryLog)
		{
			//	init log providers
			if (PrimaryLog == null)
			{
				PrimaryLog = new ApplicationLog();
				PrimaryLog.Initialize();
			}
			if (SecondaryLog == null)
			{
				SecondaryLog = new TextLog(Utilities.PathSlash(Constants.MedivatorsProgramFiles) +
										   Utilities.PathSlash("logs") +
   										   Utilities.GetAppName() +
										   ".log");
				SecondaryLog.Initialize();
			}
		}
		private void LogSettingNamesAndValues()
		{
			//	enumerate all of the Application settings to the log
			string logEntry = string.Empty;

			StringCollection sections = TextSettings.GetInstance().GetSectionNames(SettingTypes.Application);
			foreach (string section in sections)
			{
				NameValueCollection settings = TextSettings.GetInstance().GetSettings(SettingTypes.Application, section);
				foreach (string setting in settings.AllKeys)
					logEntry += string.Format("Setting {0} Value {1}\r\n", setting, settings[setting]);
			}
			Log.GetInstance().WriteLog(LogEntryType.Normal,
									   "ListenerService Application Settings: \r\n" + logEntry,
									   EventLogEntryType.Information);
		}

		#endregion
	}
}
