#! /usr/bin/python3

import argparse
from libabstractor.SparqlQuery import SparqlQuery
from libabstractor.QueryLibrary import QueryLibrary
from libabstractor.RdfGraph import RdfGraph


class Abstractor(object):
    """Abstractor main class"""

    def __init__(self):
        """Init

        Parse args and get prefixes
        """
        parser = argparse.ArgumentParser(description="Generate AskOmics abstraction from a SPARQL endpoint")

        parser.add_argument("-s", "--source", type=str, help="RDF data source (SPARQL endpoint url or path to RDF file)", required=True)
        parser.add_argument("-t", "--source-type", choices=['sparql', 'xml', 'turtle', 'nt'], help="Source format", default="sparql")

        parser.add_argument("--askomics-prefix", type=str, help="AskOmics prefix", default="http://www.semanticweb.org/user/ontologies/2018/1#")

        parser.add_argument("-o", "--output", type=str, help="Output file", default="abstraction.rdf")
        parser.add_argument("-f", "--output-format", choices=['xml', 'turtle', 'nt'], help="RDF format", default="turtle")
        parser.add_argument("--owl", default=False, action='store_true', help="Use OWL ontology")

        self.args = parser.parse_args()

    def main(self):
        """main"""
        sparql = SparqlQuery(self.args.source, self.args.source_type, self.args.askomics_prefix)
        library = QueryLibrary()

        rdf = RdfGraph(self.args.askomics_prefix)

        # Use owl ontology
        if self.args.owl:
            result = sparql.process_query(library.ontologies)
            for res in result:
                rdf.add_entities_and_relations(sparql.process_query(library.entities_and_relations_with_ontology(res["ontology"])))
                rdf.add_decimal_attributes(sparql.process_query(library.entities_and_numeric_attributes_with_ontology(res["ontology"])))
                rdf.add_text_attributes(sparql.process_query(library.entities_and_text_attributes_with_ontology(res["ontology"])))

        # All relations
        else:
            rdf.add_entities_and_relations(sparql.process_query(library.entities_and_relations))
            rdf.add_decimal_attributes(sparql.process_query(library.entities_and_numeric_attributes))
            rdf.add_text_attributes(sparql.process_query(library.entities_and_text_attributes))

        rdf.graph.serialize(destination=self.args.output, format=self.args.output_format, encoding="utf-8" if self.args.output_format == "turtle" else None)


if __name__ == '__main__':
    """main"""
    Abstractor().main()
