using Managing.Application.Abstractions;
using Managing.Domain.Bots;
using Managing.Domain.Workflows;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using static Managing.Common.Enums;

namespace Managing.Application.Bots
{
    public class SimpleBot : Bot
    {
        public readonly ILogger<TradingBot> Logger;
        private readonly IBotService _botService;
        private Workflow _workflow;

        public SimpleBot(string name, ILogger<TradingBot> logger, Workflow workflow, IBotService botService) :
            base(name)
        {
            Logger = logger;
            _botService = botService;
            _workflow = workflow;
            Interval = 100;
        }

        public override void Start()
        {
            Task.Run(() => InitWorker(Run));
            base.Start();
        }

        public async Task Run()
        {
            await Task.Run(
                async () =>
                {
                    Logger.LogInformation(Identifier);
                    Logger.LogInformation(DateTime.Now.ToString());
                    await _workflow.Execute();
                    SaveBackup();
                    Logger.LogInformation("__________________________________________________");
                });
        }

        public override void SaveBackup()
        {
            var data = JsonConvert.SerializeObject(_workflow);
            _botService.SaveOrUpdateBotBackup(User, Identifier, BotType.SimpleBot, Status, data);
        }

        public override void LoadBackup(BotBackup backup)
        {
            _workflow = JsonConvert.DeserializeObject<Workflow>(backup.Data);
        }
    }
}