import os
import sys

from rdflib import Graph
from rdflib.namespace import RDF, OWL
import tempfile
import fileinput
import subprocess

sys.path.insert(0,os.path.abspath(os.path.dirname(__file__) + '/..'))
from module import Module

class CSV2RDF(Module):

    def __init__(self, mInstanceIRI, moduleDir):
        ### ontologyIRI
        ### tarqlFile
        ### inputFile
        ### noHeader
        Module.__init__(self,  "http://topbraid.org/sparqlmotionlib#csv2rdf", mInstanceIRI, moduleDir)
        self.executable = os.path.dirname(os.path.realpath(__file__)) + "/tarql-1.0a/bin/tarql"

    def run(self):
        ontology = self.getParameter('ontologyIRI')
        file, path = tempfile.mkstemp()

        inputFile = self.moduleDir+"/"+self.getParameter('inputFile')



        try:
            with os.fdopen(file, 'w') as tmp:
                # do stuff with temp file
                for line in fileinput.input(self.moduleDir+"/"+self.getParameter('tarqlFile')):
                    lineNew = line.replace("__FN__", '"'+inputFile+'"')
                    tmp.write(lineNew)
                tmp.close()

                bashCommand = self.executable \
                                + " --ntriples" \
                                + ( " -H" if self.getParameter('noHeader') else " " ) \
                                + " " + path \
                                + " " + inputFile


                print bashCommand

                process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)

                self.outputGraph = Graph()
                self.outputGraph.parse(data=process.stdout.read(), format='nt')
                self.outputGraph.add((ontology, RDF.type,OWL.Ontology))

        finally:
            print ""
            # os.remove(path)
