import subprocess
import json

class Inference():

    @staticmethod
    def infer(network, observed):
        Inference.saveNetwork(network)
        Inference.saveObserved(observed)
        Inference.runInference()
        queryFile = open('query.json')
        queryData = json.loads(queryFile.read())
        queryFile.close()
        return queryData

    @staticmethod
    def saveObserved(observed):
        observedFile = open('observed.csv', 'w')
        for nodeId in observed:
            value = observed[nodeId]
            observedFile.write(nodeId + ',' + value + '\n')

    @staticmethod
    def runInference():
        subprocess.call(["java", "-jar", "infer.jar"])

    @staticmethod
    def saveNetwork(network):
        string = ''
        string += '<?xml version="1.0" encoding="ISO-8859-1"?>\n'
        string += '<smile version="1.0" id="Unnamed" numsamples="1000" discsamples="10000">\n'
        string += '<nodes>\n'
        for node in network:
            string += node.getXml()
        string += '</nodes>\n'
        string += '</smile>\n'
        open('network.xdsl', 'w').write(string)
