from rdflib import Graph, Namespace, URIRef, Literal, RDF, RDFS, XSD


class geometric():

    def __init__(self, IfcGeometricRepresentationSubContext, g, ontology, resource):
        self.IfcGeometricRepresentationSubContext = IfcGeometricRepresentationSubContext
        self.g = g
        self.ontology = ontology
        self.resource = resource

    def ifcGeometricRepresentationSubContextFunction(self):
        for context in self.IfcGeometricRepresentationSubContext:
            contextID = context['globalId']
            #basic information
            self.g.add((self.resource[contextID], RDF.type, self.ontology.Context))
            try:  # contextIdentifier is not always there
                contextIdentifier = context['contextIdentifier']
                self.g.add((self.resource[contextID], self.ontology.identifier, Literal(contextIdentifier)))
            except Exception:
                pass
            try:  # contextType is not always there
                contextType = context['contextType']
                self.g.add((self.resource[contextID], self.ontology.contextType, Literal(contextType)))
            except Exception:
                pass
            try:  # targetView is not always there
                contextTargetView = context['targetView']
                self.g.add((self.resource[contextID], self.ontology.targetView, Literal(contextTargetView)))
            except Exception:
                pass
            try:  # contextType is not always there
                parentContext = context['parentContext']['ref']
                self.g.add((self.resource[parentContext], RDF.type, self.ontology.Context))
                self.g.add((self.resource[contextID], self.ontology.hasParentContext, self.resource[parentContext]))
            except Exception:
                pass

            try:  # contextType is not always there
                for element in context['representationsInContext']:
                    if "ref" in list(element.keys()):
                        self.g.add((self.resource[element['ref']], RDF.type, self.ontology.Context))
                        self.g.add((self.resource[contextID], self.ontology.hasRelatedContext, self.resource[element['ref']]))
            except Exception:
                pass

        # Create RDF triples
        # Serialize and save the RDF graph to a TTL file
        file_path = "output.ttl"
        self.g.serialize(destination=file_path, format="turtle")