package de.oaa.libredeck.web.service.youtube;

import de.oaa.libredeck.web.config.YouTubeConfig;
import de.oaa.libredeck.web.model.Track;
import de.oaa.libredeck.web.service.streaming.StreamingProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@RequiredArgsConstructor
public class YouTubeProvider implements StreamingProvider {

    // https://www.youtube.com/playlist?list=PLxxxxx
    // https://music.youtube.com/playlist?list=PLxxxxx
    // https://www.youtube.com/watch?v=xxx&list=PLxxxxx  (video playing inside a playlist)
    private static final Pattern PLAYLIST_URL = Pattern.compile(
            "(?:(?:www\\.|music\\.)?youtube\\.com).*[?&]list=([A-Za-z0-9_-]+)");

    private final YouTubeApiClient apiClient;
    private final YouTubeConfig    config;

    @Override public String getId()          { return "youtube"; }
    @Override public String getDisplayName() { return "YouTube"; }

    @Override
    public boolean supportsUrl(String url) {
        return url != null && !config.getApiKey().isBlank() && PLAYLIST_URL.matcher(url).find();
    }

    @Override
    public String extractPlaylistId(String url) {
        Matcher m = PLAYLIST_URL.matcher(url);
        if (!m.find()) throw new IllegalArgumentException("Not a valid YouTube playlist URL: " + url);
        return m.group(1);
    }

    @Override
    public String fetchPlaylistTitle(String playlistId) throws IOException {
        return apiClient.fetchPlaylistTitle(playlistId);
    }

    @Override
    public List<Track> fetchTracks(String playlistId) throws IOException {
        return apiClient.fetchTracks(playlistId);
    }

    @Override
    public String fetchTrackYear(String trackId) {
        return apiClient.fetchTrackYear(trackId);
    }
}
