package be.msyben.vinylManager.tools.lyrics;

import be.msyben.vinylManager.exceptions.VinylManagerException;
import be.msyben.vinylManager.properties.Language;
import be.msyben.vinylManager.tools.log.VinylManagerLogger;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;

public final class LyricsRetriever {
    private static final String mainUrl = "https://api.lyrics.ovh/v1/";

    public static String getLyrics(String artist, String title) throws VinylManagerException {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(mainUrl).path(artist).path(title);
        try {
            Response resp = target.request().get();
            int respStatus = resp.getStatus();
            if (respStatus == 200) {
                Gson gson = new Gson();
                JsonElement element;
                try {
                    element = gson.fromJson(resp.readEntity(String.class), JsonElement.class);
                } catch (JsonSyntaxException e) {
                    throw new VinylManagerException(Language.getInstance().get("search.lyrics.error"), e);
                }
                
                if (element instanceof JsonObject obj) {
                    JsonElement lyrics = obj.get("lyrics");
                    if (lyrics != null) {
                        String ret = lyrics.getAsString();
                        return ret;
                        //return ret.replace("\r?\n\r?\n", "\r\n");                        
                    } else {
                        return "";
                    }
                } else {
                    VinylManagerLogger.log( "Mauvais format JSON");
                    throw new VinylManagerException(Language.getInstance().get("search.lyrics.error"));
                }                
            } else {                    
                VinylManagerLogger.log( "Mauvais statut de réponse :" + respStatus);
                throw new VinylManagerException(Language.getInstance().get("search.lyrics.error"));
            }
        } catch (VinylManagerException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new VinylManagerException(Language.getInstance().get("search.lyrics.error"), ex);
        }
    }
}
