using Managing.Core;
using Managing.Domain.Candles;
using Managing.Domain.Indicators;
using Managing.Domain.Shared.Rules;
using Managing.Domain.Strategies.Base;
using Skender.Stock.Indicators;
using static Managing.Common.Enums;

namespace Managing.Domain.Strategies.Trends;

public class EmaTrendIndicatorBase : EmaBaseIndicatorBase
{
    public List<LightSignal> Signals { get; set; }

    public EmaTrendIndicatorBase(string name, int period) : base(name, IndicatorType.EmaTrend)
    {
        Signals = new List<LightSignal>();
        Period = period;
    }

    public override List<LightSignal> Run(HashSet<Candle> candles)
    {
        if (candles.Count <= 2 * Period)
        {
            return null;
        }

        try
        {
            var ema = candles.GetEma(Period.Value).ToList();
            var emaCandles = MapEmaToCandle(ema, candles.TakeLast(Period.Value));

            if (ema.Count == 0)
                return null;

            var previousCandle = emaCandles[0];
            foreach (var currentCandle in emaCandles.Skip(1))
            {
                if (currentCandle.Close > (decimal)currentCandle.Ema)
                {
                    AddSignal(currentCandle, TradeDirection.Long, Confidence.None);
                }
                else
                {
                    AddSignal(currentCandle, TradeDirection.Short, Confidence.None);
                }

                previousCandle = currentCandle;
            }

            return Signals.OrderBy(s => s.Date).ToList();
        }
        catch (RuleException)
        {
            return null;
        }
    }

    public override IndicatorsResultBase GetIndicatorValues(HashSet<Candle> candles)
    {
        return new IndicatorsResultBase()
        {
            Ema = candles.GetEma(Period.Value).ToList()
        };
    }

    public void AddSignal(CandleEma candleSignal, TradeDirection direction, Confidence confidence)
    {
        var signal = new LightSignal(MiscExtensions.ParseEnum<Ticker>(candleSignal.Ticker), direction, confidence,
            candleSignal, candleSignal.Date, candleSignal.Exchange, Type, SignalType, Name);
        if (!Signals.Any(s => s.Identifier == signal.Identifier))
        {
            Signals.AddItem(signal);
        }
    }
}