using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using YTExtractor.Services.Handlers;

namespace YTExtractor.Services
{
    public class ChainYoutubeService : IYoutubeService
    {
        private readonly ILogger<ChainYoutubeService> _logger;
        private readonly YoutubeServiceHandler _firstHandler;

        public ChainYoutubeService(
            ILogger<ChainYoutubeService> logger,
            YoutubeExplodeHandler youtubeExplodeHandler,
            YtDlpHandler ytDlpHandler)
        {
            _logger = logger;
            
            // Set up the chain of responsibility
            _firstHandler = youtubeExplodeHandler;
            youtubeExplodeHandler.SetNext(ytDlpHandler);
        }

        public bool IsValidYouTubeUrl(string url)
        {
            return Regex.IsMatch(url, @"^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$");
        }

        public async Task<YtDlpInfo> GetVideoInfo(string url, string workingDir)
        {
            _logger.LogInformation("Starting chain of responsibility for video info: {Url}", url);
            return await _firstHandler.HandleVideoInfo(url, workingDir);
        }

        public async Task<string> GetSubtitles(string url, string language, string workingDir)
        {
            _logger.LogInformation("Starting chain of responsibility for subtitles: {Url}, language: {Language}", url, language);
            return await _firstHandler.HandleSubtitles(url, language, workingDir);
        }
    }
}