using System.Collections.Concurrent;
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Application.Bots;
using Managing.Common;
using Managing.Domain.Bots;
using Managing.Domain.MoneyManagements;
using Managing.Domain.Users;
using Managing.Domain.Workflows;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Managing.Application.ManageBot
{
    public class BotService : IBotService
    {
        private readonly IBotRepository _botRepository;
        private readonly IExchangeService _exchangeService;
        private readonly IMessengerService _messengerService;
        private readonly IAccountService _accountService;
        private readonly ILogger<TradingBot> _tradingBotLogger;
        private readonly ITradingService _tradingService;
        private readonly IMoneyManagementService _moneyManagementService;

        private ConcurrentDictionary<string, BotTaskWrapper> _botTasks =
            new ConcurrentDictionary<string, BotTaskWrapper>();

        public BotService(IBotRepository botRepository, IExchangeService exchangeService,
            IMessengerService messengerService, IAccountService accountService, ILogger<TradingBot> tradingBotLogger,
            ITradingService tradingService, IMoneyManagementService moneyManagementService)
        {
            _botRepository = botRepository;
            _exchangeService = exchangeService;
            _messengerService = messengerService;
            _accountService = accountService;
            _tradingBotLogger = tradingBotLogger;
            _tradingService = tradingService;
            _moneyManagementService = moneyManagementService;
        }

        public async void SaveOrUpdateBotBackup(BotBackup botBackup)
        {
            await _botRepository.InsertBotAsync(botBackup);
        }

        public BotBackup GetBotBackup(string identifier)
        {
            return _botRepository.GetBots().FirstOrDefault(b => b.Identifier == identifier);
        }

        public void SaveOrUpdateBotBackup(User user, string identifier, Enums.BotType botType, string data)
        {
            var backup = GetBotBackup(identifier);

            if (backup != null)
            {
                backup.Data = data;
                _botRepository.UpdateBackupBot(backup);
            }
            else
            {
                var botBackup = new BotBackup
                {
                    User = user,
                    Identifier = identifier,
                    BotType = botType,
                    Data = data
                };

                _botRepository.InsertBotAsync(botBackup);
            }
        }

        public class BotTaskWrapper
        {
            public Task Task { get; private set; }
            public Type BotType { get; private set; }
            public object BotInstance { get; private set; } // Add this line

            public BotTaskWrapper(Task task, Type botType, object botInstance) // Update constructor
            {
                Task = task;
                BotType = botType;
                BotInstance = botInstance; // Set the bot instance
            }
        }

        public void AddSimpleBotToCache(IBot bot)
        {
            var botTask =
                new BotTaskWrapper(Task.Run(() => bot.Start()), bot.GetType(), bot); // Pass bot as the instance
            _botTasks.AddOrUpdate(bot.Identifier, botTask, (key, existingVal) => botTask);
        }

        public void AddTradingBotToCache(ITradingBot bot)
        {
            var botTask = new BotTaskWrapper(Task.Run(() => bot.Start()), bot.GetType(), bot);
            _botTasks.AddOrUpdate(bot.Identifier, botTask, (key, existingVal) => botTask);
        }

        public List<ITradingBot> GetActiveBots()
        {
            var bots = _botTasks.Values
                .Where(wrapper => typeof(ITradingBot).IsAssignableFrom(wrapper.BotType))
                .Select(wrapper => wrapper.BotInstance as ITradingBot)
                .Where(bot => bot != null)
                .ToList();

            return bots;
        }

        public IEnumerable<BotBackup> GetSavedBots()
        {
            return _botRepository.GetBots();
        }

        public void StartBotFromBackup(BotBackup backupBot)
        {
            object bot = null;
            Task botTask = null;

            switch (backupBot.BotType)
            {
                // case Enums.BotType.SimpleBot:
                //     bot = CreateSimpleBot(backupBot.Name,
                //         null); // Assuming null is an acceptable parameter for workflow
                //     botTask = Task.Run(() => ((IBot)bot).Start());
                //     break;
                case Enums.BotType.ScalpingBot:
                    var scalpingBotData = JsonConvert.DeserializeObject<TradingBotBackup>(backupBot.Data);
                    var scalpingMoneyManagement =
                        _moneyManagementService.GetMoneyMangement(scalpingBotData.MoneyManagement.Name).Result;
                    bot = CreateScalpingBot(
                        scalpingBotData.AccountName,
                        scalpingMoneyManagement,
                        scalpingBotData.Name,
                        scalpingBotData.Ticker,
                        scalpingBotData.ScenarioName,
                        scalpingBotData.Timeframe,
                        scalpingBotData.IsForWatchingOnly,
                        scalpingBotData.BotTradingBalance);
                    botTask = Task.Run(() => InitBot((ITradingBot)bot, backupBot));
                    break;
                case Enums.BotType.FlippingBot:
                    var flippingBotData = JsonConvert.DeserializeObject<TradingBotBackup>(backupBot.Data);
                    var flippingMoneyManagement =
                        _moneyManagementService.GetMoneyMangement(flippingBotData.MoneyManagement.Name).Result;
                    bot = CreateFlippingBot(
                        flippingBotData.AccountName,
                        flippingMoneyManagement,
                        flippingBotData.Name,
                        flippingBotData.Ticker,
                        flippingBotData.ScenarioName,
                        flippingBotData.Timeframe,
                        flippingBotData.IsForWatchingOnly,
                        flippingBotData.BotTradingBalance);
                    botTask = Task.Run(InitBot((ITradingBot)bot, backupBot));
                    break;
            }

            if (bot != null && botTask != null)
            {
                var botWrapper = new BotTaskWrapper(botTask, bot.GetType(), bot);
                _botTasks.AddOrUpdate(backupBot.Identifier, botWrapper, (key, existingVal) => botWrapper);
            }
        }

        private static Action InitBot(ITradingBot bot, BotBackup backupBot)
        {
            bot.Start();
            bot.LoadBackup(backupBot);
            return () => { };
        }

        public IBot CreateSimpleBot(string botName, Workflow workflow)
        {
            return new SimpleBot(botName, _tradingBotLogger, workflow, this);
        }

        public async Task<string> StopBot(string botName)
        {
            if (_botTasks.TryGetValue(botName, out var botWrapper))
            {
                if (botWrapper.BotInstance is IBot bot)
                {
                    await Task.Run(() =>
                        bot.Stop()); // Assuming Stop is an asynchronous process wrapped in Task.Run for synchronous methods
                    return bot.GetStatus();
                }
            }

            return Enums.BotStatus.Down.ToString();
        }

        public async Task<bool> DeleteBot(string botName)
        {
            if (_botTasks.TryRemove(botName, out var botWrapper))
            {
                try
                {
                    if (botWrapper.BotInstance is IBot bot)
                    {
                        await Task.Run(() =>
                            bot.Stop()); // Assuming Stop is an asynchronous process wrapped in Task.Run for synchronous methods
                    }

                    await _botRepository.DeleteBotBackup(botName);
                    return true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return false;
                }
            }

            return false;
        }

        public Task<string> RestartBot(string botName)
        {
            if (_botTasks.TryGetValue(botName, out var botWrapper))
            {
                if (botWrapper.BotInstance is IBot bot)
                {
                    bot.Restart();
                    return Task.FromResult(bot.GetStatus());
                }
            }

            return Task.FromResult(Enums.BotStatus.Down.ToString());
        }

        public void DeleteBotBackup(string backupBotName)
        {
            _botRepository.DeleteBotBackup(backupBotName);
        }

        public void ToggleIsForWatchingOnly(string botName)
        {
            if (_botTasks.TryGetValue(botName, out var botTaskWrapper) &&
                botTaskWrapper.BotInstance is ITradingBot tradingBot)
            {
                tradingBot.ToggleIsForWatchOnly().Wait();
            }
        }

        public ITradingBot CreateScalpingBot(string accountName, MoneyManagement moneyManagement, string name,
            Enums.Ticker ticker, string scenario, Enums.Timeframe interval, bool isForWatchingOnly,
            decimal initialTradingBalance)
        {
            return new ScalpingBot(
                accountName,
                moneyManagement,
                name,
                scenario,
                _exchangeService,
                ticker,
                _tradingService,
                _tradingBotLogger,
                interval,
                _accountService,
                _messengerService,
                this,
                initialTradingBalance,
                isForWatchingOnly: isForWatchingOnly);
        }

        public ITradingBot CreateBacktestScalpingBot(string accountName, MoneyManagement moneyManagement,
            Enums.Ticker ticker, string scenario, Enums.Timeframe interval, bool isForWatchingOnly,
            decimal initialTradingBalance)
        {
            return new ScalpingBot(
                accountName,
                moneyManagement,
                "BacktestBot",
                scenario,
                _exchangeService,
                ticker,
                _tradingService,
                _tradingBotLogger,
                interval,
                _accountService,
                _messengerService,
                this,
                initialTradingBalance,
                isForBacktest: true,
                isForWatchingOnly: isForWatchingOnly);
        }

        public ITradingBot CreateFlippingBot(string accountName, MoneyManagement moneyManagement, string name,
            Enums.Ticker ticker, string scenario, Enums.Timeframe interval, bool isForWatchingOnly,
            decimal initialTradingBalance)
        {
            return new FlippingBot(
                accountName,
                moneyManagement,
                name,
                scenario,
                _exchangeService,
                ticker,
                _tradingService,
                _tradingBotLogger,
                interval,
                _accountService,
                _messengerService,
                this,
                initialTradingBalance,
                isForWatchingOnly: isForWatchingOnly);
        }

        public ITradingBot CreateBacktestFlippingBot(string accountName, MoneyManagement moneyManagement,
            Enums.Ticker ticker, string scenario, Enums.Timeframe interval, bool isForWatchingOnly,
            decimal initialTradingBalance)
        {
            return new FlippingBot(
                accountName,
                moneyManagement,
                "BacktestBot",
                scenario,
                _exchangeService,
                ticker,
                _tradingService,
                _tradingBotLogger,
                interval,
                _accountService,
                _messengerService,
                this,
                initialTradingBalance,
                isForBacktest: true,
                isForWatchingOnly: isForWatchingOnly);
        }
    }
}