import os

import sys
import pycurl
import shutil
import os.path
import urllib

import cStringIO

from rdflib import Graph
from rdflib.namespace import RDF, OWL

from module import Module

class Deploy2Sesame(Module):

    def __init__(self, mInstanceIRI, moduleDir):
        Module.__init__(self,  "http://topbraid.org/sparqlmotionlib#deploy2sesame", mInstanceIRI, moduleDir)

    def createRepository(self, sesameURL, repoName, type, inferencing):
        scriptDir = os.path.dirname(os.path.realpath(__file__))
        templateFile = scriptDir + "/templates/create-"+type+"-"+inferencing+"-repository.ttl";

        lines = '';

        tmp = open(templateFile);
        for line in tmp:
            lines += (line.replace("###REPO_PLACEHOLDER###", repoName)) + "\n"

        templateFileTmp = templateFile + "-tmp.ttl";
        shutil.copy(templateFile, templateFileTmp)
        tmp = open(templateFileTmp, 'w')
        tmp.write(lines)
        tmp.close()

        repoURL = "http://onto.fel.cvut.cz/ontologies/repositories/" + repoName
        sysRepoURL= sesameURL + "/repositories/SYSTEM"

        graph = Graph().parse(templateFileTmp,format="n3")
        self.deployOntology(graph, repoURL, sysRepoURL, True )

    def clearContext(self, contextIRI, repoURL):
        c = pycurl.Curl()
        c.setopt(c.URL, repoURL + "/statements?" + urllib.urlencode({'context' : '<'+contextIRI+'>'}))
        c.setopt(pycurl.CUSTOMREQUEST, 'DELETE')
        c.perform()
        c.close()

    def deployGraph(self, result, repoURL):
        for s, v, o in result.triples((None, RDF.type, OWL.Ontology)):
            ontologyIRI = s
            try:
                # result.serialize(format='turtle', destination=path)
                self.deployOntology(result, ontologyIRI, repoURL, self.getParameter('clearContext'))
            except:
                print "Error ... "

    def deployOntology(self, graph, contextIRI, repoURL, clearContext):
        print "* DEPLOYING "
        print "  - context IRI=", contextIRI
        print "  - repo URL=", repoURL

        url = repoURL + '/rdf-graphs/service?graph=' + contextIRI
        #    print url

        if clearContext:
            self.clearContext(contextIRI, repoURL)

        c = pycurl.Curl()
        c.setopt(c.URL, url)
        c.setopt(pycurl.POST, 1)
        data = graph.serialize(format='n3')
        c.setopt(pycurl.POSTFIELDSIZE, len(data))
        c.setopt(pycurl.READDATA, cStringIO.StringIO(data))

        c.setopt(c.HTTPHEADER, ["Content-Type: application/x-turtle;charset=UTF-8"])

        print "  - running deploy ..."
        c.perform()
        print "  - closing connection ..."
        c.close()
        print "  - done."

    #    body = buffer.getvalue()

    def run(self):
        repoName = self.getParameter('repoBaseName')
        sesameURL = self.getParameter('sesameURL')
        type = self.getParameter('type') # native/memory
        inferencing = self.getParameter('inferencing') # no/rdfs

        if not type:
            type="native"

        if not inferencing:
            inferencing="no";

        repoURL = sesameURL + '/repositories/' + repoName
        self.createRepository(sesameURL, repoName, type, inferencing)
        self.deployGraph(self.inputGraph, repoURL)
