package community.peers.internetradio.network;

import android.util.Log;

import java.net.URLEncoder;

public class Dokk
{
    public static final String SPARQL_ENDPOINT = "https://sparql.dokk.org";

    // How many radio stations to load at every request
    public static final int LOAD_LIMIT = 30;

    // Build query URL used to retrieve list of radio stations
    public static String buildQuery (String search_term, int offset)
    {
        String query = " PREFIX schema: <http://schema.org/>"
                     + " SELECT ?name ?image ?url"
                     + " WHERE {"
                     + "   [] a schema:RadioChannel ;"
                     + "      schema:name ?name ;"
                     + "      schema:image ?image ;"
                     + "      schema:url ?url ."
                     + "   FILTER REGEX (?name, \"%s\", \"i\")"
                     + " }"
                     + " ORDER BY ?name"
                     + " OFFSET %d"
                     + " LIMIT %d";

        // Escape query argument
        search_term = Dokk.escapeSparqlLiteral (search_term);

        // Replace query placeholders
        query = String.format (query, search_term, offset, Dokk.LOAD_LIMIT);

        // Return URL for GET request
        try {
            return Dokk.SPARQL_ENDPOINT +
                   "?format=json&query=" +
                   URLEncoder.encode (query, "UTF-8");
        } catch (Exception e)
        {
            return null;
        }
    }

    protected static String escapeSparqlLiteral (String literal) {
        return literal.replaceAll
            ("([\t\b\n\r\f\"'\\\\])", "\\\\$1");
    }
}