using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Knoks.Core.Data.Dao;
using Knoks.CryptoExchanges.Data.Dao;
using Knoks.Framework.DataAccess;
using Knoks.Framework.Extentions;
using Knoks.SignalsTracking;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ExchangeDao = Knoks.Core.Data.Dao.ExchangeDao;
using KnokDao = Knoks.Core.Data.Dao.KnokDao;

namespace KnoksTrackerConsoleTestApp
{
    class Program
    {
        private static SignalsTracker _signalsTracker;
        private static ILoggerFactory _loggerFactory = new LoggerFactory();

        private static ILogger _logger = _loggerFactory.CreateLogger<Program>();

        static async Task Main(string[] args)
        {
            try
            {
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .Build();

                var loggingSection = configuration.GetSection("Logging");
                _loggerFactory.AddConsole(loggingSection);
                _loggerFactory.AddDebug();

                var procExecutor = new ProcExecutor(configuration.Load<Dictionary<string, string>>("DbConnections"), _loggerFactory.CreateLogger<ProcExecutor>());
                
                var settings = configuration.Load<SignalsTrackerSettings>();
                _signalsTracker = new SignalsTracker(settings, _loggerFactory.CreateLogger<SignalsTracker>(),
                    new KnokDao(_loggerFactory.CreateLogger<KnokDao>(), procExecutor),
                    new ExchangeDao(procExecutor),
                    new ExchangePairRateDao(procExecutor)
                    );

                Console.CancelKeyPress += Console_CancelKeyPress;

                await _signalsTracker.Init();

                _signalsTracker.Start();

                _logger.LogInformation($"Signals tracker started. Press Ctrl + C to stop{Environment.NewLine}");
                await _signalsTracker.WaitForCompletion();
            }
            catch (Exception exxot)
            {
                _logger.LogError(exxot, "Pabam! We failed. Press any key to close");
            }
            finally
            {
                _signalsTracker.Dispose();
            }

            _logger.LogInformation("Tender Events Dispatcher exited.");

            Console.WriteLine($"{Environment.NewLine}Press Enter to exit{Environment.NewLine}");
            Console.ReadLine();
        }

        private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            e.Cancel = true;
            _signalsTracker.Stop();
        }
    }
}
