using Managing.Application.Abstractions.Services;
using Managing.Domain.Workflows;
using Newtonsoft.Json;
using static Managing.Common.Enums;

namespace Managing.Application.Workflows.Flows.Feeds;

public class FeedTicker : FlowBase
{
    public override List<IFlow> Children { get; set; }
    public override List<FlowParameter> Parameters { get; set; }
    public override Guid ParentId { get; }
    public override Guid Id { get; }
    public override string Output { get; set; }
    public override string Name => "Feed Ticker";
    public override FlowType Type => FlowType.FeedTicker;
    public override string Description => "This flow will take a feed and output the candles";
    public FeedTickerParameters FeedTickerParameters { get; set; }
    public override List<FlowOutput> AcceptedInputs => new();
    public override List<FlowOutput> OutputTypes => new() { FlowOutput.Candles };
    private readonly IExchangeService _exchangeService;

    public FeedTicker(IExchangeService exchangeService)
    {
        _exchangeService = exchangeService;
    }

    public async override Task Execute(string input)
    {
        MapParameters();
        var candles = await _exchangeService.GetCandlesInflux(FeedTickerParameters.Exchange, FeedTickerParameters.Ticker, DateTime.Now.AddDays(-11), FeedTickerParameters.Timeframe);

        Output = JsonConvert.SerializeObject(candles.ToHashSet());

        if(Children != null && Children.Count > 0)
        {
            foreach (var child in Children)
            {
                await child.Execute(Output);
            }
        }
    }

    public override void MapParameters()
    {
        FeedTickerParameters = new FeedTickerParameters();
        foreach (var param in Parameters)
        {
            if (param.Name == nameof(FeedTickerParameters.Ticker))
                FeedTickerParameters.Ticker = (Ticker)Enum.Parse(typeof(Ticker), param.Value);
            if (param.Name == nameof(FeedTickerParameters.Exchange))
                FeedTickerParameters.Exchange = (TradingExchanges)Enum.Parse(typeof(TradingExchanges), param.Value);
            if (param.Name == nameof(FeedTickerParameters.Timeframe))
                FeedTickerParameters.Timeframe = (Timeframe)Enum.Parse(typeof(Timeframe), param.Value);
        }
    }
}

public class FeedTickerParameters
{
    public TradingExchanges Exchange { get; set; }
    public Ticker Ticker { get; set; }
    public Timeframe Timeframe { get; set; }
}
