#!/usr/bin/python
"""
.. module:: owl2rdflib

owl2rdflib
******

:Description: owl2rdflib

    Generates a python file with a RDFlib Namespace object with the classes and attributes of a owl file

:Authors:
    bejar

:Version:

:Date:  16/12/2020
"""

__author__ = 'bejar'

import argparse
import time

from rdflib import Graph, RDF, OWL, URIRef


def chop(uriref):
    """
    returns the last part of the uriref
    :param uriref:
    :return:
    """
    if '#' in uriref:
        return uriref.toPython().split("#")[-1]
    elif '/' in uriref:
        return uriref.toPython().split("/")[-1]
    else:
        return uriref


def print_vocabulary(f, voc, last):
    """
    Print the terms in the list

    :param f:
    :param voc:
    :param last:
    :return:
    """
    if voc != []:
        if last:
            for n in voc[:-1]:
                f.write(f"        '{n}',\n")
            f.write(f"        '{voc[-1]}'\n")
        else:
            for n in voc:
                f.write(f"        '{n}',\n")


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', required=True, help='Input file')
    parser.add_argument('--output', default=None, help='Output file')
    parser.add_argument('--format', required=True, choices=['xml', 'turtle'], help='File format')

    args = parser.parse_args()
    if args.output is None:
        out = args.input.split('.')[0]
    else:
        out = args.output.split('.')[0]

    g = Graph()

    g.parse(args.input, format=args.format)

    cls = [chop(c) for c in g.subjects(RDF.type, OWL.Class) if c != OWL.Thing and isinstance(c, URIRef)]
    opr = [chop(c) for c in g.subjects(RDF.type, OWL.ObjectProperty) if isinstance(c, URIRef)]
    dpr = [chop(c) for c in g.subjects(RDF.type, OWL.DatatypeProperty) if isinstance(c, URIRef)]
    inst = [chop(c) for c in g.subjects(RDF.type, OWL.NamedIndividual) if isinstance(c, URIRef)]

    onto = [c for c in g.subjects(RDF.type, OWL.Ontology)]

    f = open(out + '.py', 'w')
    f.write("\"\"\"\n")
    f.write(f".. module:: {out}\n")
    f.write(f"\n Translated by owl2rdflib\n")
    f.write(f"\n Translated to RDFlib from ontology {onto[0].toPython()}\n")
    f.write(f"\n :Date {time.strftime('%d/%m/%Y %H:%M:%S', time.localtime())}\n")

    f.write("\"\"\"\n")
    f.write("from rdflib import URIRef\n")
    f.write("from rdflib.namespace import ClosedNamespace\n")

    f.write("\n")
    f.write(f"{out.upper()} =  ClosedNamespace(\n")
    f.write(f"    uri=URIRef('{onto[0].toPython()}'),\n")
    f.write(f"    terms=[\n")
    f.write(f"        # Classes\n")
    print_vocabulary(f, cls, opr == [] and dpr == [] and inst == [])
    f.write(f"\n        # Object properties\n")
    print_vocabulary(f, opr, dpr == [] and inst == [])
    f.write(f"\n        # Data properties\n")
    print_vocabulary(f, dpr, inst == [])
    f.write(f"\n        # Named Individuals\n")
    print_vocabulary(f, inst, True)
    f.write(f"    ]\n")
    f.write(f")\n")

    f.close()
