namespace JeepConsole
{
    using OT.COM.SignalerMessage;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Microsoft.Extensions.Configuration;
    using log4net;
    using System.Reflection;
    using log4net.Config;
    using System.Text;


    internal static class Program
    {

        private readonly static ILog _log = LogManager.GetLogger(typeof(Program));

        [STAThread]
        private static void Main()
        {
            LoadLog4netConfig();

            System.Threading.Mutex mu = new System.Threading.Mutex(true, string.Format("Global\\{0}", typeof(Program).GUID), out bool IsAppRunning);

            if (!IsAppRunning)
            {
                _log.Error("Leave Program without doing anything(Mutex)");
                mu.Dispose();
                Environment.Exit(1);
            }

            try
            {
#if DEBUG
                string sSettingFile = "appsettings.Development.json";
#else 
            string sSettingFile = "appsettings.json" ;
#endif

                string[] saCmd = System.Environment.GetCommandLineArgs();
                _log.Info(saCmd);
                StringBuilder sb = new StringBuilder("AP Start! ");

                int nIndex = 0;
                foreach (string sCmd in saCmd)
                {
                    sb.Append($"Para[{nIndex++}] = '{sCmd}'");
                }

                _log.Info(sb.ToString());

                _log.Info($"Current directory: {Directory.GetCurrentDirectory()}");

                IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile(sSettingFile, optional: true, reloadOnChange: true).Build();

                IEnumerable<IConfigurationSection> ics = configuration.GetSection("appSettings").GetChildren();

                Dictionary<string, string> dicSetting = new Dictionary<string, string>();
                foreach (IConfigurationSection ic in ics)
                {
                    dicSetting.Add(ic.Key, ic.Value);
                }

                if (saCmd.Length == 4 && saCmd[1] == "CMD")
                {
                    string sURL = $"{dicSetting["apiserver"]}/Cmd";
                    _log.Info($"URL = {sURL} ");
                    SendWebApiRequest swr = new SendWebApiRequest();
                    CRequestMessage crm = new CRequestMessage()
                    {
                        module = saCmd[2],
                        method = saCmd[3]
                    };

                    CReqestPack crqp = new CReqestPack
                    {
                        Reqs = new List<CReqestItem>()
                {
                    new CReqestItem(){ Req = crm }
                }
                    };

                    string sRes = swr.RunEncryptRequest(sURL, crqp, out string o_sRes);
                    if (sRes != null)
                    {
                        _log.Error($"Result = {sRes}");
                    }
                    else
                    {
                        _log.Info($"Response = {o_sRes}");
                    }

                }
                else
                {
                    _log.Info($"NO SUPPORT COMMAND. Ex JeepConsole.exe CMD RPT.ReportSchedule Run");
                }
            }
            catch
            {
                string sMsg = $"{nameof(Main)} unknwon exception.";
                System.Diagnostics.Debug.Write(sMsg);
                _log.Error(sMsg);
            }
            _log.Info("AP Close! ");

        }

        private static void LoadLog4netConfig()
        {
            var repository = LogManager.CreateRepository(
                    Assembly.GetEntryAssembly(),
                    typeof(log4net.Repository.Hierarchy.Hierarchy)
                );
            XmlConfigurator.Configure(repository, new FileInfo("Log4Net.config"));
        }
    }
}