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

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

    // https://tidal.com/browse/playlist/uuid or https://listen.tidal.com/playlist/uuid
    private static final Pattern PLAYLIST_URL = Pattern.compile(
            "tidal\\.com(?:/browse)?/playlist/([\\w\\-]+)",
            Pattern.CASE_INSENSITIVE);

    private final TidalApiClient apiClient;

    @Override public String getId()          { return "tidal"; }
    @Override public String getDisplayName() { return "Tidal"; }

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

    @Override
    public String extractPlaylistId(String url) {
        Matcher m = PLAYLIST_URL.matcher(url);
        if (m.find()) return m.group(1);
        throw new IllegalArgumentException("Not a valid Tidal 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);
    }
}
