from rdflib import Graph, BNode
from rdflib.namespace import RDFS
from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace, Literal

#from subprocess import call

#call("./../../Ontologies/s-get http://155.207.131.19:3030/Mokos_18_1_7_47/data default >> ../../Ontologies/data.ttl", shell=True)

#HERE 
#list_of_DSO = ["http://delab.csd.auth.gr/ontologies/2018/SAO#","http://delab.csd.auth.gr/ontologies/2018/DSO#", "http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive#", "http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive-AVP#", "http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive-AVP-instances#","http://delab.csd.auth.gr/ontologies/2018/RDO-instances#"]
list_of_DSO = [] 
list_of_rbo = ["http://delab.csd.auth.gr/ontologies/2018/RBO#"]
list_of_lo = ["http://delab.csd.auth.gr/ontologies/2018/LO#"]
#list_of_RMO = ["RMO", "RMO-instances", "DSO-AOCS-instances", "<http://delab.csd.auth.gr/ontologies/2018/RDO-instances"]
#list_of_RMO = ["RMO", "RMO-instances", "DSO-Automotive-AVP-instances", "<http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive-AVP-instances"]
DSO = ["http://delab.csd.auth.gr/ontologies/2018/DSO#"]

Dictionary_Data = {}
Dictionary_Data_list = []

#g = Graph()
#g.load(Ontology_file, format="turtle")

'''def find_subclass_domain_range():
    file2 = open(r"../../Ontologies/instances.txt","w+") 

    for subj, obj in g.subject_objects(predicate=RDFS.subClassOf):
        subClass = subj + "$"+ obj + "\n"
        file2.write(subClass)
    for subj, obj in g.subject_objects(predicate=RDFS.domain):
        subClass = subj + "$"+ obj + "\n"
        file2.write(subClass)
    for subj, obj in g.subject_objects(predicate=RDFS.range):
        subClass = subj + "$"+ obj + "\n"
        file2.write(subClass)'''


def findsubclass(g):
    subclasslist = [] 
    for subj, obj in g.subject_objects(predicate=RDFS.subClassOf):
        subClass = subj + "$"+ obj + "\n"
        subclasslist.append(subClass)
    return subclasslist


def get_i_instances(keyword):
    out_list = []
    per = URIRef("http://delab.csd.auth.gr/ontologies/2018/"+keyword)
    for s, p, o in g.triples((None, RDF.type, per)):
        split = s.split("#")
        out_list.append(split[len(split) - 1])
    return tuple((str(n), str(n)) for n in (out_list))


'''Get Verbs - return tuple'''
def get_verb_instances(keyword):
    get_file_and_instances(keyword)
    keywordspl = keyword.split("#")
    in_list = []
    out_list = []
    with open('../../Ontologies/instances.txt') as f:
        for data in f:
            if (data.strip()).endswith(keyword):
                spliter_1 = data.split('$')
                spliter_2 = spliter_1[0].split("#")
                in_list.append(spliter_2[len(spliter_2) - 1])
    for extra in in_list:
        per = URIRef("http://delab.csd.auth.gr/ontologies/2018/LO#" +extra)
        for s, p, o in g.triples((None, RDF.type, per)):
            spl = s.split("#")
            out_list.append(str(spl[1]))
    return tuple((str(n), str(n)) for n in (out_list))

'''Get Verbs - return tuple'''
def get_verb_file_and_instances(keyword, g):
    get_file_and_instances(keyword, g)
    keywordspl = keyword.split("#")
    in_list = []
    out_list = []
    with open('../../Ontologies/instances.txt') as f:
        for data in f:
            if (data.strip()).endswith(keyword):
                spliter_1 = data.split('$')
                spliter_2 = spliter_1[0].split("#")
                in_list.append(spliter_2[len(spliter_2) - 1])
    for extra in in_list:
        per = URIRef("http://delab.csd.auth.gr/ontologies/2018/LO#" +extra)
        for s, p, o in g.triples((None, RDF.type, per)):
            spl = s.split("#")
            out_list.append(extra + " : " + str(spl[1]))
    return tuple((str(n), str(n)) for n in (out_list))


'''Get Instaces - return tuple'''
def get_instances(keyword, list_of_DSO):
    keywordspl = keyword.split("#")
    in_list = [keywordspl[len(keywordspl)-1]]
    out_list = []
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
                spl = s.split("#")
                in_list.append(spl[len(spl) - 1])
    for extra in in_list:
        for uri in list_of_DSO:
            p = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDF.type, p)):
                spl = s.split("#")
                uri = spl[len(spl) - 2].split("/")
                out_list.append(spl[len(spl) - 1])
                #new code
                out_list.append(extra)
    return tuple((str(keywordspl[len(keywordspl)-1]+" : "+out_list[n+1]+" : "+out_list[n]), str(keywordspl[len(keywordspl)-1]+" : "+out_list[n+1]+" : "+out_list[n]) ) for n in range(0, len(out_list), 2))


# A list with the values and the file that is the instance
out_list = []
# A dict with all the info of classes, subclasses and instances
info_dict = {}


'''Get Instaces - return tuple'''
def get_instances_g(keyword, g, list_of_DSO):
    keywordspl = keyword.split("#")
    in_list = [keywordspl[len(keywordspl)-1]]
    out_list = []
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
                #print('res',s)
                spl = s.split("#")
                in_list.append(spl[len(spl) - 1])
    for extra in in_list:
        for uri in list_of_DSO:
            p = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDF.type, p)):
                spl = s.split("#")
                uri = spl[len(spl) - 2].split("/")
                out_list.append(spl[len(spl) - 1])
                #new code
                out_list.append(extra)
    return tuple((str(keywordspl[len(keywordspl)-1]+" : "+out_list[n+1]+" : "+out_list[n]), str(keywordspl[len(keywordspl)-1]+" : "+out_list[n+1]+" : "+out_list[n]) ) for n in range(0, len(out_list), 2))


# A list with the values and the file that is the instance
out_list = []
# A dict with all the info of classes, subclasses and instances
info_dict = {}

def get_file_and_instances(keyword, g):
    for ns_prefix, namespace in g.namespaces():
        if ('http://delab.csd.auth.gr/ontologies/2018/DSO' in namespace):
            list_of_DSO.append(str(namespace))
    list_of_DSO.append("http://delab.csd.auth.gr/ontologies/2018/SAO#")
    list_of_DSO.append("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#")
    out_list = []
    keywordspl = keyword.split("#")
    in_list = [keywordspl[len(keywordspl)-1]]
    #find one layer down System: Subclass
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
                spl = s.split("#")
                in_list.append(spl[len(spl) - 1])
    #print(in_list)
    #find two layer down System: Subclass : Instance
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDF.type, per)):
                spl = s.split("#")
                uri = spl[len(spl) - 2].split("/")
                out_list.append(keywordspl[len(keywordspl)-1]+" : "+extra+" : " +spl[len(spl) - 1])
                out_list.append(str(spl[len(spl) - 2]))
    return out_list


#Instances and Comments
'''def get_dmo_instance_and_comment(keyword):
    dmo_dic = {}
    dic_list = []
    mid_list = []
    out_list_com = []
    keywordspl = keyword.split("#")
    in_list = [keywordspl[len(keywordspl)-1]]
    with open('../../Ontologies/instances.txt') as f:
        for data in f:
            if (data.strip()).endswith(keyword):
                spliter_1 = data.split('$')
                spliter_2 = spliter_1[0].split("#")
                in_list.append(spliter_2[len(spliter_2) - 1])
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDF.type, per)):
                spl = s.split("#")
                uri = spl[len(spl) - 2].split("/")
                mid_list.append(extra)
                mid_list.append(spl[len(spl) - 1])
                dmo_dic = {'Class': extra, 'instance':spl[len(spl) - 1]}
                dic_list.append(dmo_dic)
    #need to find if instances have comment with their description
    #for now it returns only the instances
    for extra in mid_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((per, RDFS.comment, None)):
                spl = s.split("#")
                uri = spl[len(spl) - 2].split("/")
                out_list_com.append(str(extra))
                out_list_com.append((str(o).replace("\r","")).replace("\n",""))
    return dic_list'''



#Classes and Comments
def get_dmo_classes_and_comment(keyword, g, list_of_DSO):
    dic_list = []
    dic_list_in = []
    dmo_dic_backup = {}
    out_list_instance = []
    keywordspl = keyword.split("#")
    section = keywordspl[len(keywordspl)-1]
    in_list = [section]
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            dmo_dic_in={}
            #get Instance of Upper (System, Function etc.)
            for s, p, o in g.triples((None, RDF.type, per)):
                spl = s.split("#")
                uri = spl[len(spl) - 2].split("/")
                find_comment_gen_instance = ""
                for urired2 in list_of_DSO:
                    pop = URIRef(urired2 + spl[len(spl) - 1])
                    for q1, w1, m1 in g.triples((pop, RDFS.comment, None)):
                        find_comment_gen_instance = (str(m1).replace("\r","")).replace("\n","")
                dmo_dic_in = {'Instance': spl[len(spl) - 1], "Comment": find_comment_gen_instance}
                dic_list_in.append(dmo_dic_in)
            #get Instance of First Subclass
            for s, p, o in g.triples((None, RDFS.subClassOf, per)):
                spl = s.split("#")
                out_list_instance.append(spl[len(spl) - 1])
                comment = str(spl[len(spl) - 1])
                Clcomment=""
                for sas, pas, oas in g.triples((s, RDFS.comment, None)):
                    Clcomment = (str(oas).replace("\r","")).replace("\n","")
                instance_list = []
                instance_dict = {}
                subclass_list = []
                for uri in list_of_DSO:
                    per = URIRef(uri +comment)
                    for s2, p2, o2 in g.triples((None, RDF.type, per)):
                        spl = s2.split("#")
                        find_comment_main_instance = ""
                        for urired2 in list_of_DSO:
                            pop = URIRef(urired2 + spl[len(spl) - 1])
                            for q1, w1, m1 in g.triples((pop, RDFS.comment, None)):
                                find_comment_main_instance = (str(m1).replace("\r","")).replace("\n","")
                        #print("Instance", spl[len(spl) - 1], "Comment", find_comment_main_instance)
                        instance_dict = {"Instance": spl[len(spl) - 1], "Comment": find_comment_main_instance}
                        instance_list.append(instance_dict)
                    for s1, p1, o1 in g.triples((None, RDFS.subClassOf, per)):
                        spl1 = s1.split("#")
                        #subclass_list.append(spl1[len(spl1) - 1])
                        subclas_name = spl1[len(spl1) - 1]
                        kop = URIRef(uri + spl1[len(spl1) - 1])
                        find_comment = ""
                        find_comment_instance = ""
                        for q, w, m in g.triples((kop, RDFS.comment, None)):
                            find_comment = (str(m).replace("\r","")).replace("\n","")
                        sub_ins = []
                        for urired in list_of_DSO:
                            per3 = URIRef(urired + spl1[len(spl1) - 1])
                            for s2, p2, o2 in g.triples((None, RDF.type, per3)):
                                spl2 = s2.split("#")
                                for urired2 in list_of_DSO:
                                    kop2 = URIRef(urired2 + spl2[len(spl2) - 1])
                                    for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
                                        find_comment_instance = (str(m1).replace("\r","")).replace("\n","")
                                sub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": find_comment_instance}
                                sub_ins.append(sub_ins_dict) 
                        ###############################
                        #get Instance of all subclasses
                        subsubclass_list= get_Classes_Dictionary(subclas_name, list_of_DSO, g)
                        suclass_dict = {'SubClass_name': subclas_name, 'SubclassComment':find_comment, 'InstanceOfSubclass': sub_ins, 'SubSubClass' : subsubclass_list}
                        subclass_list.append(suclass_dict)
                        ############################################
                dmo_dic_backup = {"Class": str(comment), "Comment":Clcomment, 'Subclass': subclass_list, 'Instance_of_Class':instance_list}
                dic_list.append(dmo_dic_backup)
    Dictionary_Data = { "Name":section, "TheClasses" : dic_list, "GeneralInstances": dic_list_in}
    #print(Dictionary_Data)
    return Dictionary_Data


def get_Classes_Dictionary(name, list_of_DSO, g):
    #subsubsub_ins_dict = {}
    subsubsubsuclass_dict = {}
    subsubsubsubclass_list = []
    for uris in list_of_DSO:
        per2 = URIRef(uris + name)
        for k1, l1, h1 in g.triples((None, RDFS.subClassOf, per2)):
            spl1 = k1.split("#")
            subsubsubsubclas_name = spl1[len(spl1) - 1]
            kop = URIRef(uris + spl1[len(spl1) - 1])
            subsubsubfind_comment = ""
            subsubsubfind_comment_instance = ""
            for q, w, m in g.triples((kop, RDFS.comment, None)):
                subsubsubfind_comment = (str(m).replace("\r","")).replace("\n","")
            subsubsubsub_ins_dict = {}
            subsubsubsub_ins = []
            for subsubsuburired in list_of_DSO:
                per3 = URIRef( subsubsuburired + spl1[len(spl1) - 1])
                for s2, p2, o2 in g.triples((None, RDF.type, per3)):
                    spl2 = s2.split("#")
                    for suburired2 in list_of_DSO:
                        kop2 = URIRef(suburired2 + spl2[len(spl2) - 1])
                        for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
                            subsubsubfind_comment_instance = (str(m1).replace("\r","")).replace("\n","")
                    subsubsubsub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": subsubsubfind_comment_instance}
                    subsubsubsub_ins.append(subsubsubsub_ins_dict)
            #get current Subclass -Subclasses / Instances
            newsubclass_list = get_Classes_Dictionary(subsubsubsubclas_name, list_of_DSO, g)
            subsubsubsuclass_dict = {'SubSubClass_name': subsubsubsubclas_name, 'SubSubclassComment':subsubsubfind_comment, 'SubInstanceOfSubclass': subsubsubsub_ins, 'SubSubClass': newsubclass_list}
            subsubsubsubclass_list.append(subsubsubsuclass_dict) 
    return subsubsubsubclass_list
    



#Classes of classes and Comments
def get_dmo_classes_of_classes_and_comment(keyword, list_of_DSO):
    dmo_dic = {}
    dic_list = []
    out_list_instance = []
    out_list_com = []
    mid_list = []
    find_comment = False
    keywordspl = keyword.split("#")
    in_list = [keywordspl[len(keywordspl)-1]]
    for extra in in_list:
        for uri in list_of_DSO:
            per = URIRef(uri +extra)
            for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
                spl = s.split("#")
                out_list_instance.append(spl[len(spl) - 1])
    for comment in out_list_instance:
        for uri in list_of_DSO:
            per = URIRef(uri +comment)
            for s, p, o in g.triples((None, RDFS.subClassOf, per)):
                spl = s.split("#")
                out_list_com.append(str(comment))
                out_list_com.append(spl[len(spl) - 1])
                kop = URIRef(uri + spl[len(spl) - 1])
                find_comment = ""
                for q, w, m in g.triples((kop, RDFS.comment, None)):
                    out_list_com.append((str(m).replace("\r","")).replace("\n",""))
                    find_comment = (str(m).replace("\r","")).replace("\n","")
                    dmo_dic = {"Class": str(comment),'Subclass': spl[len(spl) - 1], "SubclassComment":find_comment}
                    dic_list.append(dmo_dic)
    return(dic_list)


'''Get Instaces - return list'''
def get_instances_list(keyword, g):
    f = findsubclass(g)
    an_list=[]
    for data in f:
        if (data.strip()).endswith(keyword):
            spliter_1 = data.split('$')
            spliter_2 = spliter_1[0].split("#")
            an_list.append(spliter_2[len(spliter_2) - 1])
    return an_list




'''Find Boilerplate subject of each main - return list'''
def get_subjects(bnodes_uriref):
    setOfElems = set()
    duplicate_uri = []
    bnodes = []
    rdf_syntax = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'

    for elem in range (len(bnodes_uriref)):
        if not bnodes_uriref[elem] in setOfElems:
            setOfElems.add(bnodes_uriref[elem])  
        else:
            duplicate_uri.append(bnodes_uriref[elem])
        if   rdf_syntax == str(bnodes_uriref[elem]) :
            bnodes = bnodes_uriref[:elem] 

    try:
        duplicate_uri.remove(URIRef(rdf_syntax)) 
    except:
        pass
    
    subject_list = []
    for i in duplicate_uri:
        if i in bnodes:
            spliter = str(i).split("#")
            subject_list.append(str(spliter[1]))
    subject_list = list(filter(("nil").__ne__, subject_list))
    subject_list = list(filter(("in").__ne__, subject_list))
    return(subject_list)


'''Find Boilerplate classes between subject and verb - return list'''
def get_related_to_subject(bnodes_uriref):
    related_to_subject_list = []
    bnodes_uriref = [str(i) for i in bnodes_uriref]
    for rel_to_sub in bnodes_uriref:
        if "isRelatedToSubject" in rel_to_sub:
            tmp = rel_to_sub.split("isRelatedToSubject")
            if tmp[1] != '':
                related_to_subject_list.append(tmp[1])
    return(related_to_subject_list)


'''Find Boilerplate Verb - return list'''
def get_verb(bnodes_uriref, g):
    verb_list = []
    out_list =[]
    bnodes_uriref = [str(i) for i in bnodes_uriref]
    for rel_to_sub in bnodes_uriref:
        if "LO" in rel_to_sub:
            tmp = rel_to_sub.split("#")
            if tmp[1] != '':
                verb_list.append(tmp[1])
    for extra in verb_list:
        per = URIRef("http://delab.csd.auth.gr/ontologies/2018/LO#" +extra)
        for s, p, o in g.triples((None, RDF.type, per)):
            spl = s.split("#")
            out_list.append(str(spl[1]))
    return(out_list)


'''Check if Boilerplate has quantifier - return list'''
def check_quantifier(bnodes_uriref):
    bnodes_uriref = [str(i) for i in bnodes_uriref]
    quantity = [(rel_to_sub) for rel_to_sub in bnodes_uriref if "isRelatedToQuantity" in rel_to_sub]
    uom = [(rel_to_sub) for rel_to_sub in bnodes_uriref if "isRelatedtoUOM" in rel_to_sub]
    if quantity or uom:
        return True


'''Find Boilerplate Attribute - return list'''
def get_attribute(main, bnodes_uriref, subjects, related_subjects, verbs):
    bnodes = []
    attribute_list = []
    bnodes_uriref = [str(i) for i in bnodes_uriref]
    #print(main, bnodes_uriref)

    for attribute in bnodes_uriref:
        #if "isRelatedToSubject" in attribute:
        #    pass
        if "isRelatedTo" in attribute:
            attribute_list.append(attribute)
    #print(main, attribute_list)
    attribute_list = list(filter(("Action").__ne__, attribute_list))
    attribute_list = list(filter(("Attribute").__ne__, attribute_list))
    attribute_list = list(filter(("Quantity").__ne__, attribute_list))
    attribute_list = list(filter(("UOM").__ne__, attribute_list))
    attribute_list = list(filter(("nil").__ne__, attribute_list))
    attribute_list = list(filter(("in").__ne__, attribute_list))
    #discuss with kostas if this needed
    attribute_list = list(filter(("TraversingConcept").__ne__, attribute_list))
    
    tmp_list = []
    #print(bnodes_uriref)
    for i in bnodes_uriref:
        if not "isRelatedTo" in i:
            if not "isRelatedto" in i:
                tmp = i.split("#")
                if(len(tmp) > 1):
                    if tmp[1] != '':
                        tmp_list.append(tmp[1])
    
    tmp_list = list(filter(("nil").__ne__, tmp_list))
    tmp_list = list(filter(("in").__ne__, tmp_list))
    tmp_list = list(filter(("Restriction").__ne__, tmp_list))
    tmp_list = list(filter(("Class").__ne__, tmp_list))
    tmp_list = list(filter(("Action").__ne__, tmp_list))
    tmp_list = list(filter(("Quantity").__ne__, tmp_list))
    tmp_list = list(filter(("UnitOfMeasurement").__ne__, tmp_list))
    for i in subjects:
        tmp_list = list(filter((i).__ne__, tmp_list))
    for i in related_subjects:
        tmp_list = list(filter((i).__ne__, tmp_list))
    for i in verbs:
        tmp_list = list(filter((i).__ne__, tmp_list))

    res = attribute_list + tmp_list
    res = list(dict.fromkeys(res))
    return(res)


'''Find Main syntax - return a dict with the syntax'''
def get_main_sytax_inference(g):
    get_main = get_instances_list("RBO#Main", g)
    main_dict = {}
    for main in get_main:
        main_dict[main] = {}
        #main_dict[main]["Id"] = main
        main_dict[main]["Subject"] = []
        main_dict[main]["Related_to_Subject"] = []
        main_dict[main]["Verbs"] = []
        main_dict[main]["Quantifier"] = None
        main_dict[main]["Attributes"] = []

        bnodes = []
        p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main)
        for s, p, o in g.triples((p, None, None)):
            if isinstance(o, BNode):
                bnodes.append(o)
                data = []
                for o1, p1, s1 in g.triples((o, None, None)):
                    if isinstance(s1, URIRef):
                        data.append(str(s1))
                    if isinstance(s1, BNode):
                        for objects1 in g.objects(subject=BNode(s1)):
                            if isinstance(objects1, BNode):
                                for objects2 in g.objects(subject=BNode(objects1)):
                                    if isinstance(objects2, URIRef):
                                        data.append(str(objects2))
                                    elif isinstance(objects2, BNode):
                                        for objects3 in g.objects(subject=BNode(objects2)):
                                            if isinstance(objects3, URIRef):
                                                if(not 'nil' in str(objects3)):
                                                    data.append(str(objects3))
                strings_with_substring_subState = [string for string in data if "isRelatedToSubjectState" in string]
                if(len(strings_with_substring_subState) > 0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_subState]
                    for i in tmp_list:
                        i=i.split('#')
                        main_dict[main]["Related_to_Subject"].append(i[1])
                strings_with_substring_subItem = [string for string in data if "isRelatedToSubjectItem" in string]
                if(len(strings_with_substring_subItem) > 0 and len(strings_with_substring_subState)==0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_subItem]
                    for i in tmp_list:
                        i=i.split('#')
                        main_dict[main]["Related_to_Subject"].append(i[1])

                strings_with_substring_sub = [string for string in data if "isRelatedToSubject" in string]
                if(len(strings_with_substring_sub) > 0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_sub]
                    for i in tmp_list:
                        i=i.split('#')
                        main_dict[main]["Subject"].append(i[1])
                strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
                if(len(strings_with_substring_verb) > 0 ):
                    tmp_list = [string for string in  data if string not in strings_with_substring_verb]
                    for i in tmp_list:
                        for s, p, o in g.triples((None, RDF.type, URIRef(i))):
                            spl = s.split("#")
                            main_dict[main]["Verbs"].append(spl[1])
                strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
                if(len(strings_with_substring_quan) > 0):
                    main_dict[main]["Quantifier"] = True
                strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
                if(len(strings_with_substring_attr) > 0 and len(strings_with_substring_verb) == 0  and len(strings_with_substring_quan)==0 and len(strings_with_substring_sub)==0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_attr]
                    tmp_list2 = [string for string in tmp_list if "boolean" not in string]
                    for i in tmp_list2:
                        i=i.split('#')
                        main_dict[main]["Attributes"].append(i[1])
    return main_dict


'''Find Main syntax - return a dict with the syntax'''
def get_main_sytax(g):
    get_main = get_instances_list("RBO#Main",g)
    main_dict = {}
    main_dict_list = []
    for main in get_main:
        main_dict[main] = {}
        main_dict[main]["Id"] = main
        main_dict[main]["Subject"] = []
        main_dict[main]["Related_to_Subject"] = []
        main_dict[main]["Verbs"] = []
        main_dict[main]["Quantifier"] = None
        main_dict[main]["Attributes"] = []

        bnodes = []
        p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main)
        for s, p, o in g.triples((p, None, None)):
            if isinstance(o, BNode):
                bnodes.append(o)
                data = []
                for o1, p1, s1 in g.triples((o, None, None)):
                    if isinstance(s1, URIRef):
                        data.append(str(s1))
                    if isinstance(s1, BNode):
                        for objects1 in g.objects(subject=BNode(s1)):
                            if isinstance(objects1, BNode):
                                for objects2 in g.objects(subject=BNode(objects1)):
                                    if isinstance(objects2, URIRef):
                                        data.append(str(objects2))
                                    elif isinstance(objects2, BNode):
                                        for objects3 in g.objects(subject=BNode(objects2)):
                                            if isinstance(objects3, URIRef):
                                                if(not 'nil' in str(objects3)):
                                                    data.append(str(objects3))
                strings_with_substring_subState = [string for string in data if "isRelatedToSubjectState" in string]
                if(len(strings_with_substring_subState) > 0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_subState]
                    for i in tmp_list:
                        i=i.split('#')
                        main_dict[main]["Related_to_Subject"].append(i[1])
                strings_with_substring_subItem = [string for string in data if "isRelatedToSubjectItem" in string]
                if(len(strings_with_substring_subItem) > 0 and len(strings_with_substring_subState)==0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_subItem]
                    for i in tmp_list:
                        i=i.split('#')
                        main_dict[main]["Related_to_Subject"].append(i[1])

                strings_with_substring_sub = [string for string in data if "isRelatedToSubject" in string]
                if(len(strings_with_substring_sub) > 0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_sub]
                    for i in tmp_list:
                        i=i.split('#')
                        main_dict[main]["Subject"].append(i[1])
                strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
                if(len(strings_with_substring_verb) > 0 ):
                    tmp_list = [string for string in  data if string not in strings_with_substring_verb]
                    for i in tmp_list:
                        for s, p, o in g.triples((None, RDF.type, URIRef(i))):
                            spl = s.split("#")
                            main_dict[main]["Verbs"].append(spl[1])
                strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
                if(len(strings_with_substring_quan) > 0):
                    main_dict[main]["Quantifier"] = True
                strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
                if(len(strings_with_substring_attr) > 0 and len(strings_with_substring_verb) == 0  and len(strings_with_substring_quan)==0 and len(strings_with_substring_sub)==0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
                    tmp_list = [string for string in  data if string not in strings_with_substring_attr]
                    tmp_list2 = [string for string in tmp_list if "boolean" not in string]
                    for i in tmp_list2:
                        i=i.split('#')
                        main_dict[main]["Attributes"].append(i[1])

        main_dict_list.append(main_dict[main])
    return main_dict_list


'''Find Prefix syntax - return a dict with the syntax'''
def get_prefix_syntax(g):
    prefix_dict={}
    prefix_list = []
    get_prefix = get_instances_list("RBO#Prefix",g)
    for prefix in get_prefix:
        prefix_list.extend(get_instances_list(prefix, g))
    for prefix in prefix_list:
        prefix_dict[prefix] = {}
        #prefix_dict[prefix]["Verbs"] = []
        #prefix_dict[prefix]["Attribute"] = []
        #prefix_dict[prefix]["Subject"] = []
        bnodes_uriref = find_triples(prefix, g)
        subclass_data = []
        for per in bnodes_uriref:
            tmp = get_instances_list(str(per), g)
            bnodes_uriref.extend(tmp)
            for i in tmp:
                subclass_data.append(i)
        for pre in subclass_data:
            prefix_dict[prefix][str(pre)+"_Verbs"] = []
            prefix_dict[prefix][str(pre)+"_Attribute"] = []
            prefix_dict[prefix][str(pre)+"_Subject"] = []
            prefix_dict[prefix][str(pre)+"_Quantifier"] = None
            bnodes = []
            p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + pre)
            for s, p, o in g.triples((p, None, None)):
                if isinstance(o, BNode):
                    bnodes.append(o)
                    data = []
                    for o1, p1, s1 in g.triples((o, None, None)):
                        if isinstance(s1, URIRef):
                            data.append(str(s1))
                        if( 'syntaxOrder' in p1):
                            order = int(s1)
                        if isinstance(s1, BNode):
                            for objects1 in g.objects(subject=BNode(s1)):
                                if isinstance(objects1, BNode):
                                    for objects2 in g.objects(subject=BNode(objects1)):
                                        if isinstance(objects2, URIRef):
                                            data.append(str(objects2))
                                        elif isinstance(objects2, BNode):
                                            for objects3 in g.objects(subject=BNode(objects2)):
                                                if isinstance(objects3, URIRef):
                                                    if(not 'nil' in str(objects3)):
                                                        data.append(str(objects3))
                    strings_with_substring_subState = [string for string in data if "isRelatedToStimulus" in string]
                    if( (len(strings_with_substring_subState) > 0) and order == 0):
                        tmp_list = [string for string in  data if string not in strings_with_substring_subState]
                        for i in tmp_list:
                            i=i.split('#')
                            prefix_dict[prefix][str(pre)+"_Subject"].append(i[1])
                    strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
                    if(len(strings_with_substring_verb) > 0 ):
                        tmp_list = [string for string in  data if string not in strings_with_substring_verb]
                        for i in tmp_list:
                            for s, p, o in g.triples((None, RDF.type, URIRef(i))):
                                spl = s.split("#")
                                prefix_dict[prefix][str(pre)+"_Verbs"].append(spl[1])
                    strings_with_substring_state = [string for string in data if "isRelatedToState" in string]
                    if(len(strings_with_substring_state) > 0 ):
                        tmp_list = [string for string in  data if string not in strings_with_substring_state]
                        for i in tmp_list:
                            i = i.split("#")
                            prefix_dict[prefix][str(pre)+"_Verbs"].append(i[1])
                    strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
                    if(len(strings_with_substring_quan) > 0):
                        prefix_dict[prefix][str(pre)+"_Quantifier"] = True
                    strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
                    if(len(strings_with_substring_attr) > 0 and order==0 and len(strings_with_substring_verb) == 0  and len(strings_with_substring_quan)==0 and len(strings_with_substring_subState)==0 ):
                        tmp_list = [string for string in  data if string not in strings_with_substring_attr]
                        for i in tmp_list:
                            i=i.split('#')
                            prefix_dict[prefix][str(pre)+"_Subject"].append(i[1])
                    elif(len(strings_with_substring_attr) > 0 and len(strings_with_substring_verb) == 0  and len(strings_with_substring_quan)==0 and len(strings_with_substring_subState)==0 ):
                        tmp_list = [string for string in  data if string not in strings_with_substring_attr]
                        for i in tmp_list:
                            i=i.split('#')
                            prefix_dict[prefix][str(pre)+"_Attribute"].append(i[1])
    return prefix_dict        


'''Return Verb list Of Prefixes'''
def get_prefix_verbs(g):
    prefix_dict={}
    prefix_list = []
    verblist =[]
    out_list = []
    get_prefix = get_instances_list("RBO#Prefix", g)
    for prefix in get_prefix:
        prefix_list.extend(get_instances_list(prefix, g))
    for prefix in prefix_list:
        bnodes_uriref = find_triples(prefix, g)
        subclass_data = []
        for per in bnodes_uriref:
            tmp = get_instances_list(str(per), g)
            bnodes_uriref.extend(tmp)
            for i in tmp:
                subclass_data.append(i)
        for pre in subclass_data:
            tmp_list2 = find_triples(pre, g)
            tmp_list2 = [str(i) for i in tmp_list2]
            #add verbs
            if tmp_list2:
                ver = get_verb(tmp_list2, g)
                if (len(ver)==0):
                    out_list.append('Is : is')
                    verblist.append('Is : is')
                else:
                    verblist.extend(ver)
                    for extra in tmp_list2:
                        if "LO" in str(extra):
                            per = URIRef(extra)
                            for s, p, o in g.triples((None, RDF.type, per)):
                                spl = s.split("#")
                                out_list.append(extra.split("#")[1] + " : " + str(spl[1]))
    return tuple((str(n), str(n)) for n in (set(out_list)))


'''The new prefix syntaxt parser'''
def get_prefix_new_syntax(g):
    bnodes = []
    prefix_list = []
    get_prefix = get_instances_list("RBO#Prefix", g)
    for prefix in get_prefix:
        prefix_list.extend(get_instances_list(prefix, g))
#owl:allValuesFrom
    for prefix in prefix_list:
        per = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + prefix)
        #per2 = URIRef("http://www.w3.org/2002/07/owl#allValuesFrom")
        bnodes_uriref = find_triples(prefix, g)
        subclass_data = []
        #print(bnodes_uriref)
        for per in bnodes_uriref:
            tmp = get_instances_list(str(per), g)
            bnodes_uriref.extend(tmp)
            for i in tmp:
                subclass_data.append(i)
        print(subclass_data)
        #




'''Find the triples of the prefix - return list.type(URIRef)'''
def find_triples(prefix, g):
    bnodes = []
    URIRef_list = []
    per = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + prefix)
    for s, p, o in g.triples((per, None, None)):
        if isinstance(o, BNode):
            bnodes.append(o)
    bnodes.sort()

    for bn in bnodes:
        for objects in g.objects(subject=BNode(bn)):
            if isinstance(objects, BNode):
                bnodes.append(objects)     
    bnodes.sort()
    bnodes_uriref = []

    for bn in bnodes:
        for objects in g.objects(subject=BNode(bn)):
            if isinstance(objects, URIRef):
                bnodes_uriref.append(objects)
    return bnodes_uriref