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

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 SpotifyProvider implements StreamingProvider {

    // https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M?si=...
    private static final Pattern PLAYLIST_URL = Pattern.compile(
            "open\\.spotify\\.com/playlist/([A-Za-z0-9]+)");
    // spotify:playlist:37i9dQZF1DXcBWIGoYBM5M
    private static final Pattern PLAYLIST_URI = Pattern.compile(
            "spotify:playlist:([A-Za-z0-9]+)");

    private final SpotifyApiClient apiClient;

    @Override public String getId()          { return "spotify"; }
    @Override public String getDisplayName() { return "Spotify"; }

    @Override
    public boolean supportsUrl(String url) {
        if (url == null) return false;
        return PLAYLIST_URL.matcher(url).find() || PLAYLIST_URI.matcher(url).find();
    }

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

    @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);
    }
}
