#!/usr/bin/python
"""
Master thesis project, automaticly populating tables.n
Author: Bas Raven

----------------------
    - Returning initial tests for simple Python program
    - Same as test 5, but without the given label
----------------------
"""
#print (__doc__)

class sparqlquerybuilder():
    
    from SPARQLWrapper import SPARQLWrapper, JSON
    sparql = SPARQLWrapper("http://dbpedia.org/sparql")
    
    import logging
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    

    prefixes = """
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX : <http://dbpedia.org/resource/>
    PREFIX dbpedia2: <http://dbpedia.org/property/>
    PREFIX dbpedia: <http://dbpedia.org/>
    PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    """

    
    
    def buildConnectionsQuery(self, propertyarray):
        
        
        # First build the body
        counter = 0
        selects = ''
        body1 = ''
        for prop in propertyarray:
            body1 += '''
            ?propertyuri'''+str(counter)+''' rdfs:label "'''+prop+'''"@en .            
            #?connectionuri'''+str(counter)+''' rdfs:label ?connectionlabel'''+str(counter)+''' .
            #FILTER(langMatches(lang(?connectionlabel'''+str(counter)+'''), "EN"))
            
            ?propertyuri'''+str(counter)+''' rdfs:domain ?superclass .
            
        
            ?subject ?propertyuri'''+str(counter)+''' ?connectionoutput'''+str(counter)+''' .
            
            #OPTIONAL {?connectionoutput'''+str(counter)+''' rdfs:label ?opt'''+str(counter)+'''  .
            #FILTER(langMatches(lang(?opt'''+str(counter)+'''), "EN")) }  .
            
            
            
            '''
            
            selects += ' ?connectionoutput'+str(counter)+' ?opt'+str(counter) +"\n"
            counter +=1
            
        
        
        # Secondly build the subjectpart
        #'''+selects+ '''
        q = self.prefixes+'''
        SELECT ?superclass ?superclasstypelabel  
        WHERE {
        '''+body1 
        
        q += '''
        
        
            ?superclasstype rdf:type  ?superclass .
            ?superclasstype     rdfs:label ?superclasstypelabel .

                         
            
            FILTER(langMatches(lang(?superclasstypelabel), "EN")) .
        
        
        } '''
        # LIMIT '''+str(len(propertyarray))+'''
   
        
        return q    
        
    
    def getConnections(self, propertyarray, encoding='utf8'):
        """
        Returns the domain of the provided entry
        """
        q = self.buildConnectionsQuery(propertyarray)
        
        self.logging.info(q)
        self.sparql.setQuery(q)
        
        
        
        self.sparql.setReturnFormat(self.JSON)
        results = self.sparql.query().convert()
        """
        rarray=[]
        for result in results["results"]["bindings"]:
            counter = 0
            rarrayitems = []
            for prop in propertyarray:
                if ('opt'+str(counter)) in result: #Use the opt value
                    rarrayitems.append(result['opt'+str(counter)]['value'].encode(encoding))
                    
                else: #Use the connectionoutput value
                    rarrayitems.append(result['connectionoutput'+str(counter)]['value'].encode(encoding))
                counter += 1
                    
            rarray.append([result["subjectlabel"]["value"].encode(encoding), rarrayitems])#.encode(encoding))
                
        
        #from tools import removeMatrixDuplicates 
        #return removeMatrixDuplicates(rarray)
        return rarray[0]
        """
        #import json
        #print json.dumps(results)

    
    
    
    
    
    
    
    
    
    
    
    
    def getHeaderInfo(self):

        """ Example 1:
        
        Country name       anthem        language        population density (/sqkm)
        --------------

        
        
        """
        
        
        
        propertyarray1 = [ 'capital', 'area total (km2)',  'anthem','population density (/sqkm)']
        propertyarray2 = ['manager club', 'team']
        
        

        self.getConnections(propertyarray2[:2])
        
        #for name in names:
        #    print self.getConnections(name, propertyarray)
            
        
        
        
        
        
        
        
        
        
if  __name__ =='__main__':
    sparqlquerybuilder().getHeaderInfo()
        
