using e_suite.Scheduler.Scheduler;
using eSuite.Core.Clock;

namespace e_suite.Scheduler;

public class ScheduledJob
{
    private readonly IClock _clock;
    private DateTimeOffset _nextScheduledExecution = DateTimeOffset.MinValue;
    private DateTimeOffset _lastExecuted = DateTimeOffset.MinValue;
    private ISchedule _schedule = null!;

    public ScheduledJob(IClock clock)
    {
        _clock = clock;
    }

    public IJob Job { get; set; } = null!;

    public ISchedule Schedule
    {
        get => _schedule;
        set
        {
            if (_schedule == value)
                return;

            _schedule = value;
            GetNextScheduledExecution();
        }
    }

    public DateTimeOffset LastExecuted
    {
        get => _lastExecuted;
        set
        {
            if (_lastExecuted == value)
                return;

            _lastExecuted = value;
            GetNextScheduledExecution();
        }
    }
    
    public DateTimeOffset NextScheduledExecution
    {
        get
        {
            if (_nextScheduledExecution == DateTimeOffset.MinValue)
            {
                GetNextScheduledExecution();
            }

            return _nextScheduledExecution;
        }
    }

    private void GetNextScheduledExecution()
    {
        _nextScheduledExecution = Schedule.NextScheduledExecution(_clock);
    }
}