#!/usr/bin/python

import sys
sys.path.append('suds-0.3.7-py2.6.egg')

import socket
import os
from string import join
import urllib
import re
from datetime import datetime, timedelta


import suds

#see: http://www.carto.net/papers/svg/gui/scrollbar/index.svg for scrooling (table/svg)

queryParams = ''
issparql = True
diccURIs = {}

pathlenght = 10

def repla_href(m):
    s = m.group(0)
    uri = s[s.find('"')+1:s.rfind('"')]
    params = { 'updateURI' : uri, 'query': queryParams, 'isSparql' : issparql }
    encoded_params = urllib.urlencode(params)
    url = 'provqueryTool.cgi?' + encoded_params
    s = '#value# #a href="' + url + '"##'
    return s
    
def repla_href1(m):
    global queryParams
    global issparql
    global diccURIs
    uri = m.group(1)
    params = { 'updateURI' : uri, 'query': queryParams, 'isSparql' : issparql }
    encoded_params = urllib.urlencode(params)
    url = 'provqueryTool.cgi?' + encoded_params.replace('&', '&amp;')
    s = 'xlink:href="' + url + '" target="_top"'
    return s

class ProvWSClient:
    def __init__(self):
        self.client = suds.client.Client("http://convulsion.doc.ic.ac.uk:55050/provenanceWS_provQueryServer-1.0.0-SNAPSHOT/ProvenanceWSProvQueryTool?wsdl", faults=False)
        #self.client = suds.client.Client("http://convulsion.doc.ic.ac.uk:55050/GeneralII-0.0.1-SNAPSHOT/ProvenanceServerWebService1?wsdl")
#suds.client.Client("http://convulsion.doc.ic.ac.uk:55050/provenanceGeneralWS-0.0.1-SNAPSHOT/ProvenanceServerWebService?wsdl")
 
    def get_table_svg(self, q, l, b):
        try:
            return self.client.service.getTable_SVGViewForQuery(q, l, b)
        except suds.WebFault, detail:
            print details
   
    def get_table_svg_AND_highlight(self, q, l, b, uriTohighlight):
        try:
            return self.client.service.getTable_SVGViewForQueryAndHighlight(q, l, b, uriTohighlight)
        except suds.WebFault, detail:
            print details
    
    def updateOPMEntityLinks(self, svg):
         return re.sub('xlink:href=["]([^"]+)["]', repla_href1, svg)
    
    def generateTable(self, strtable):
        #print 'q', queryParams, 'sp', issparql
        strtable = re.sub('#value uri=["].+["]#', repla_href, strtable)
        strtable = strtable.replace('#table#', '<table>').\
                                                        replace('#/table#', '</table>').\
                                                        replace('#encab#', '<tr>').\
                                                        replace('#/encab#', '</tr>').\
                                                        replace('#var#', '<th>').\
                                                        replace('#/var#', '</th>').\
                                                        replace('#data#', '').\
                                                        replace('#/data#', '').\
                                                        replace('#row#', '<tr>').\
                                                        replace('#/row#', '</tr>').\
                                                        replace('#value#', '<td>').\
                                                        replace('#/value#', '</a></td>').\
                                                        replace('#a href', '<a href').\
                                                        replace('##', '>')
        return '<h4>Results:</h4><br>' + strtable

queryparams = "0@DATE1:2013-08-01@DATE2:2013-08-02";
isSparql = True
p = ProvWSClient()
(a, data) = p.get_table_svg( queryparams, pathlenght, isSparql )
print a#data
if data.find('------- SVG graph -------') >=0:
    data = data.split('------- SVG graph -------')
    #print data[0]
    html = open('pcpal.html').read()
    html = html.replace('<!--#QUERY_ANSWER#-->', p.generateTable(data[0]))
    svg = p.updateOPMEntityLinks( data[1] )
    html = html.replace('<!--#GRAPH#-->', '<div class="text" style="text-align:left;"><h4>Graph:</h4></div><br><object data="img.svg" type="image/svg+xml"></object>' )
    f = open('generated_pcpal.html', 'w')
    f.write(html)
    f.close()
	
