using Managing.Core;
using Managing.Domain.Candles;
using Managing.Infrastructure.Evm.Subgraphs.Models;
using static Managing.Common.Enums;

namespace Managing.Infrastructure.Evm.Extensions;

public static class PriceExtensions
{
    public static List<Candle> GetCandles(this Round[] prices, Timeframe timeframe, Ticker ticker)
    {
        int timezoneOffset = - (int)(new DateTimeOffset(DateTime.UtcNow).Offset.TotalSeconds);
        var CHART_PERIODS = new Dictionary<Timeframe, int>
        {
            { Timeframe.FiveMinutes, 60 * 5 },
            { Timeframe.FifteenMinutes, 60 * 15 },
            { Timeframe.OneHour, 60 * 60 },
            { Timeframe.FourHour, 60 * 60 * 4 },
            { Timeframe.OneDay, 60 * 60 * 24 }
        };
        int periodTime = CHART_PERIODS[timeframe];

        if (prices.Count() < 2)
        {
            return new List<Candle>();
        }

        List<Candle> candles = new List<Candle>();
        Round first = prices[0];
        int prevTsGroup = (int)Math.Floor((decimal)first.UnixTimestamp / periodTime) * periodTime;
        decimal prevPrice = decimal.Parse(first.Value);
        decimal o = prevPrice;
        decimal h = prevPrice;
        decimal l = prevPrice;
        decimal c = prevPrice;
        for (int i = 1; i < prices.Count(); i++)
        {
            var current = prices[i];
            int tsGroup = (int)Math.Floor((decimal)current.UnixTimestamp / periodTime) * periodTime;
            if (prevTsGroup != tsGroup)
            {
                candles.Add(new Candle
                {
                    OpenTime = DateHelpers.GetFromUnixTimestamp(prevTsGroup + timezoneOffset),
                    Date = DateHelpers.GetFromUnixTimestamp(tsGroup + timezoneOffset),
                    Open = o,
                    High = h,
                    Low = l,
                    Close = c,
                    Timeframe = timeframe
                });
                o = c;
                h = Math.Max(o, c);
                l = Math.Min(o, c);
            }
            c = decimal.Parse(current.Value);
            h = Math.Max(h, c);
            l = Math.Min(l, c);
            prevTsGroup = tsGroup;
        }

        return candles.Select(x => new Candle
        {
            OpenTime = x.OpenTime,
            Date = x.Date,
            Open = x.Open,
            Close = x.Close,
            High = x.High,
            Low = x.Low,
            Timeframe = x.Timeframe,
            Exchange = TradingExchanges.Evm,
            Ticker = ticker.ToString()
        }).ToList();
    }
}
