import hashlib
import random
import re
import string
import urllib.parse
import dokk.sparql as sparql

from datetime import datetime, timezone
from dokk import settings
from rdflib import Graph, URIRef, Literal
from string import Template

def topic_exists(id):
    """
    Check if a topic already exists.
    
    :param id: ID of the topic.
    """
    
    query = Template("""
        PREFIX : <dokk:/>
        PREFIX dokk: <https://ontology.dokk.org/>

        ASK {
                [] dokk:id "$id" ;
                   a dokk:Topic .
            }
    """).substitute(id = sparql.escape_literal(id))
    
    response = sparql.query_public(query)
    
    return response['boolean']

def get_topic(id):
    """
    Retrieve a topic.
    
    :param id: Topic ID.
    """
    
    query = Template("""
        PREFIX : <dokk:/>
        PREFIX dokk: <https://ontology.dokk.org/>

        DESCRIBE *
        WHERE   {
                    ?s dokk:id "$id" ;
                       a dokk:Topic .
                }
    """).substitute(id = sparql.escape_literal(id))
    
    response = sparql.query_public(query)
    
    return response

def list_topics(name):
    """
    List topics that start with the give name string.
    
    :param name: Search term to match at the beginning of the string.
    """
    
    query = Template("""
        PREFIX : <dokk:/>
        PREFIX dokk: <https://ontology.dokk.org/>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

        SELECT ?id
        WHERE   {
                    [] dokk:id ?id ;
                       a dokk:Topic .
                    
                    FILTER STRSTARTS(LCASE(?id), LCASE("$search_term"))
                }
        ORDER BY ?id
        LIMIT 10
    """).substitute(search_term = sparql.escape_literal(name))
    
    response = sparql.query_public(query)
    
    return response
