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

namespace Managing.Domain.Strategies;

public class EmaTrendStrategy : EmaBaseStrategy
{
    public List<Signal> Signals { get; set; }

    public EmaTrendStrategy(string name, int period) : base(name, StrategyType.EmaTrend)
    {
        Signals = new List<Signal>();
        Period = period;
    }

    public override List<Signal> Run()
    {
        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 StrategiesResultBase GetStrategyValues()
    {
        return new StrategiesResultBase()
        {
            Ema = Candles.GetEma(Period.Value).ToList()
        };
    }

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