using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Plugin.SRFPlay.Services.Interfaces;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Plugin.SRFPlay.ScheduledTasks;

/// <summary>
/// Scheduled task that checks and manages sport livestream recordings.
/// Runs every 2 minutes to start scheduled recordings when streams go live
/// and stop recordings when they end.
/// </summary>
public class RecordingSchedulerTask : IScheduledTask
{
    private readonly ILogger<RecordingSchedulerTask> _logger;
    private readonly IRecordingService _recordingService;

    /// <summary>
    /// Initializes a new instance of the <see cref="RecordingSchedulerTask"/> class.
    /// </summary>
    /// <param name="logger">The logger.</param>
    /// <param name="recordingService">The recording service.</param>
    public RecordingSchedulerTask(
        ILogger<RecordingSchedulerTask> logger,
        IRecordingService recordingService)
    {
        _logger = logger;
        _recordingService = recordingService;
    }

    /// <inheritdoc />
    public string Name => "Process SRF Play Recordings";

    /// <inheritdoc />
    public string Description => "Checks scheduled recordings and starts/stops them as needed";

    /// <inheritdoc />
    public string Category => "SRF Play";

    /// <inheritdoc />
    public string Key => "SRFPlayRecordingScheduler";

    /// <inheritdoc />
    public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
    {
        _logger.LogDebug("Processing SRF Play recordings");
        progress?.Report(0);

        try
        {
            await _recordingService.ProcessRecordingsAsync(cancellationToken).ConfigureAwait(false);
            progress?.Report(100);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing recordings");
            throw;
        }
    }

    /// <inheritdoc />
    public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
    {
        return new[]
        {
            new TaskTriggerInfo
            {
                Type = TaskTriggerInfo.TriggerInterval,
                IntervalTicks = TimeSpan.FromSeconds(30).Ticks
            }
        };
    }
}
