using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;
using FI.FIC.DataProviders.Alert;
using Foresight.Service.Monitor;

namespace IronIntel.Contractor
{
    public class IronIntelService : ServiceBase
    {
        private static bool IsTrue(string s)
        {
            return (string.Compare(s, "true", true) == 0 || string.Compare(s, "yes", true) == 0 || string.Compare(s, "1", true) == 0);
        }

        ForesightMonitorServiceBase SvcMon = null;
        private AlertManagerEx _Alert = null;

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);

            SystemParams.CreateDbObjects();

            FI.FIC.FICHostEnvironment.RunInServices = true;            
            if (IsTrue(ConfigurationManager.AppSettings["StartFICAlertService"]))
            {
                _Alert = new AlertManagerEx();
                _Alert.Start();
                Log.WriteMessage("FIC Alert Service Started.");
            }
            if (IsTrue(ConfigurationManager.AppSettings["StartFICChartSubscribeService"]))
            {
                FI.FIC.Email.ChartProvider.StartSend();
                Log.WriteMessage("FIC Chart Subscribe Service Started.");
            }
            FI.FIC.Cache.TableCache.Start();
            Log.WriteMessage("FIC table cache service started.");

            string[] monendpoints = SystemParams.GetMonitorServiceAddresses();
            if (monendpoints != null && monendpoints.Length > 0)
            {
                SvcMon = new ForesightMonitorServiceBase(monendpoints);
                SvcMon.Category = "Fleet-FICAlert";
                if (!string.IsNullOrWhiteSpace(SvcMon.ServiceInfo.Description))
                {
                    SvcMon.ServiceInfo.Description = SvcMon.ServiceInfo.Description + "\r\n" + SystemParams.CompanyID;
                }
                else
                {
                    SvcMon.ServiceInfo.Description = "Fleet FIC Alert Service - " + SystemParams.CompanyID;
                }
                SvcMon.Notes = "Fleet FIC Alert Service";
                SvcMon.Start();
            }
        }

        protected override void OnStop()
        {
            if(SvcMon!=null)
            {
                SvcMon.Stop();
            }

            if(_Alert!=null)
            {
                _Alert.Stop();
                _Alert = null;
            }
            
            FI.FIC.Email.ChartProvider.EndSend();
            FI.FIC.Cache.TableCache.Stop();

            base.OnStop();
        }
    }
}
