#!/usr/bin/python
# -*- coding: utf-8 -*-

# Interface python para hacer consultas en sparql
from SPARQLWrapper import SPARQLWrapper, JSON, XML
import cgi


#recuperar datos enviados por el formulario(localhost/form1.html)
form = cgi.FieldStorage() 
id_ortho = form.getvalue('id')
bd_origen = form.getvalue('bd1')
bd_destino =form.getvalue('bd2')

#la consulta sparql
sparql = SPARQLWrapper("http://sele.inf.um.es/sparql")
if bd_destino == 'todos':# es decir buscar en todas las bases de datos 
     queryString = """       
	PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema>
	PREFIX uniprot: <http://uniprot.org/uniprot/>
	PREFIX oma: <http://omabrowser.org/oma/vps/>
	PREFIX owl: <http://www.w3.org/2002/07/owl#>
	PREFIX aphidbase:<http://identifiers.org/aphidbase.transcript/>
	PREFIX beebase:<http://genomes.missouri.edu:8080/hymenopteramine/keywordSearchResults.do?searchTerm=>
	PREFIX beetlebase:<http://identifiers.org/beetlebase/>
	PREFIX ena:<http://identifiers.org/ena.embl/>
	PREFIX flybase:<http://identifiers.org/beetlebase/flybase/>
	PREFIX genedb:<http://genedb.org/gene/>
	PREFIX metazoa:<http://identifiers.org/ensembl.metazoa/>
	PREFIX protist:<http://identifiers.org/ensembl.protist/>
	PREFIX jgi:<http://identifiers.org/img.taxon/>
	PREFIX pombase:<http://identifiers.org/pombase/>
	PREFIX tair:<http://identifiers.org/tair.locus/>
	PREFIX vectorbase:<http://identifiers.org/vectorbase/>
	PREFIX wormbase:<http://identifiers.org/wormbase/>
	PREFIX spbase:<http://www.spbase.org/SpBase/search/viewAnnoGeneInfo.php?spu_id=>
	PREFIX nasoniabase:<http://genomes.missouri.edu:8080/hymenopteramine/keywordSearchResults.do?searchTerm=>
	PREFIX string:<http://string-db.org/interactions/>
	PREFIX treefam:<http://treefam.org/sequence/>
	PREFIX ensembl:<http://ensembl.org/Multi/Search/Results?q=>
	PREFIX silkdb:<http://silkworm.genomics.org.cn/cgi-bin/gbrowse_details/silkdb?class=GenePrediction;name=>
	PREFIX kegg:<http://identifiers.org/kegg/>
	PREFIX inparanoid:<http://inparanoid.sbc.su.se/cgi-bin/gene_search.cgi?id#>
	PREFIX jgicap:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Capca1&id=>
	PREFIX jgidap:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Dappu1&id=>
	PREFIX jgitriad:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Triad1&id=>
	PREFIX jginem:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Nemve1&id=>
	PREFIX parasite:<http://parasite.wormbase.org/Meloidogyne_hapla_prjna29083/Gene/Summary?g=>
	PREFIX parasite2:<http://parasite.wormbase.org/Heterorhabditis_bacteriophora_prjna13977/Gene/Summary?g=>
	PREFIX metapac:<http://metazoa.ensembl.org/Amphimedon_queenslandica/Gene/Summary?db=otherfeatures;t=>
	PREFIX metazoacep:<http://metazoa.ensembl.org/Atta_cephalotes/Gene/Summary?db=otherfeatures;g=>

	    select ?s ?o WHERE {bd1:id ?p ?o. 
	    		        ?s ?p ?o}"""
else: # devuelve resutltado para una base especifica
   queryString = """       
	PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema>
	PREFIX treefam: <http://treefam.org/sequence/>
	PREFIX uniprot: <http://uniprot.org/uniprot/>
	PREFIX oma: <http://omabrowser.org/oma/vps/>
	PREFIX owl: <http://www.w3.org/2002/07/owl#>
	PREFIX aphidbase:<http://identifiers.org/aphidbase.transcript/>
	PREFIX beebase:<http://genomes.missouri.edu:8080/hymenopteramine/keywordSearchResults.do?searchTerm=>
	PREFIX beetlebase:<http://identifiers.org/beetlebase/>
	PREFIX ena:<http://identifiers.org/ena.embl/>
	PREFIX flybase:<http://identifiers.org/beetlebase/flybase/>
	PREFIX genedb:<http://genedb.org/gene/>
	PREFIX metazoa:<http://identifiers.org/ensembl.metazoa/>
	PREFIX protist:<http://identifiers.org/ensembl.protist/>
	PREFIX jgi:<http://identifiers.org/img.taxon/>
	PREFIX pombase:<http://identifiers.org/pombase/>
	PREFIX tair:<http://identifiers.org/tair.locus/>
	PREFIX vectorbase:<http://identifiers.org/vectorbase/>
	PREFIX wormbase:<http://identifiers.org/wormbase/>
	PREFIX spbase:<http://www.spbase.org/SpBase/search/viewAnnoGeneInfo.php?spu_id=>
	PREFIX nasoniabase:<http://genomes.missouri.edu:8080/hymenopteramine/keywordSearchResults.do?searchTerm=>
	PREFIX string:<http://string-db.org/interactions/>
	PREFIX treefam:<http://treefam.org/sequence/>
	PREFIX ensembl:<http://ensembl.org/Multi/Search/Results?q=>
	PREFIX silkdb:<http://silkworm.genomics.org.cn/cgi-bin/gbrowse_details/silkdb?class=GenePrediction;name=>
	PREFIX kegg:<http://identifiers.org/kegg/>
	PREFIX inparanoid:<http://inparanoid.sbc.su.se/cgi-bin/gene_search.cgi?id=>
	PREFIX jgicap:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Capca1&id=>
	PREFIX jgidap:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Dappu1&id=>
	PREFIX jgitriad:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Triad1&id=>
	PREFIX jginem:<http://genome.jgi.doe.gov/cgi-bin/dispGeneModel?db=Nemve1&id=>
	PREFIX parasite:<http://parasite.wormbase.org/Meloidogyne_hapla_prjna29083/Gene/Summary?g=>
	PREFIX parasite2:<http://parasite.wormbase.org/Heterorhabditis_bacteriophora_prjna13977/Gene/Summary?g=>
	PREFIX metapac:<http://metazoa.ensembl.org/Amphimedon_queenslandica/Gene/Summary?db=otherfeatures;t=>
	PREFIX metazoacep:<http://metazoa.ensembl.org/Atta_cephalotes/Gene/Summary?db=otherfeatures;g=>

	  select ?s ?o WHERE {bd1:id ?p ?o .?s ?p ?o. FILTER(regex(str(?o),"bd2"))}"""
queryString = queryString.replace("bd2",bd_destino)


queryString = queryString.replace("id",id_ortho)
queryString = queryString.replace("bd1",bd_origen) 


# ejecutar la consulta
sparql.setQuery(queryString)

#salida xml
#sparql.setReturnFormat(XML)
#resultas = sparql.query().convert()
#print resultas.toxml()

# salida json
sparql.setReturnFormat(JSON)

#comprobar el estado de conexion al servidor
try:
  results = sparql.query().convert()
  requestGood = True
except Exception, e:
  results = str(e)
  requestGood = False

print """Content-type: text/html

<html><head><title>RESULTADOS(python)</title>

<link type="text/css" rel="stylesheet" href="http://sele.inf.um.es/buscar_mapeo/css/estilo1.css">
</head><body>
<a href=\"javascript:history.go(-1)\">Volver</a>
"""
if requestGood == False:
  print "<h3 align='center'>No se puede conectar al servidor!!</h3>"
  print "<p>" + results + "</p>"
elif (len(results["results"]["bindings"]) == 0):# sin resultados
  print "<h3 align='center'>No hay Resultados!</h3>"
  print "<p></br></br>Buscar en <a href=http://sele.inf.um.es/buscar_mapeo/buscar_map.cgi?id="+id_ortho 		      +"&bd1="+bd_origen+"&bd2=todos> todas</a> las bases de datos."
else:# hay salidas, meter resultados en una tabla html
  print "<h3 align='center'>Mapeo de -<span style='color: green'>" + id_ortho + "</span>-(" + bd_origen +"-" + bd_destino + ")</h3>"
  print "<table align='center'><thead align='center'>"
  print "<th>n\xb0</th>"
  print "<th>&nbsp;&nbsp;"+bd_origen+"</th>"
  print "<th align='center'>"+bd_destino+"</th><thead>"
  
  i=len(results["results"]["bindings"])
  j = 0
  for result in results["results"]["bindings"]:
    bdd1 = result["s"]["value"]
    bdd2 = result["o"]["value"]
    j += 1
    print "<tr><td>",j 
    print "</td><td>&nbsp;&nbsp;<a href=\"" + bdd1 + "\">" + bdd1 + "</a></td>"
    print "<td><a href=\"" + bdd2 + "\">" + bdd2 + "</a></td></tr>"
    if j == i:
       break
   
    
    


print "</body></html>"    



