from rdflib import RDF, RDFS, Graph, URIRef, Literal
from rest_framework.generics import ListAPIView, RetrieveUpdateDestroyAPIView, ListAPIView
from rest_framework import permissions

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from reqman.apps.reqtool.rest_api.serializers.requirements import BoilerplateGroupClassesInstancesSerializer, BoilerplateGroupDictionarySerializer

from reqman.apps.reqtool.models.main_req import Main
from reqman.apps.reqtool.rest_api.serializers.main_req import MainSerializer

from reqman.apps.permissions import IsOwnerOrReadOnly
from reqman.apps.reqtool.rest_api.services import fuseki, inference
from reqman.apps.reqtool.rest_api.services.parse_ontologies import get_main_sytax, get_main_sytax_inference

from rest_framework.response import Response
from rest_framework.views import APIView

from reqman.apps.reqtool.models.main_req import SHALL_CHOICES #, MAIN_SYNTAX

from reqman.apps.reqtool.models.requirements import BoilerplateData, BoilerplateGroupClassesInstances, BoilerplateGroupDictionary
from rest_framework.exceptions import APIException



class MainListAPIView(ListAPIView):
    """
    API view to retrieve list of posts or create new
    """
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = MainSerializer
    #
    queryset = Main.objects.all()

    def get_queryset(self):
        group_pk = self.kwargs['boilerplate']
        #print(group_pk)
        queryset_main = Main.objects.filter(boilerplate_of_main = group_pk)
        return queryset_main

    #Custom actions when POST
    def perform_create(self, serializer):
        serializer.save()
        #print the data of the post
        #write_fuseki = fuseki.FusekiActions()
        #write_fuseki.write(serializer.data)

class MainDetailsAPIView(RetrieveUpdateDestroyAPIView):
    """
    API view to retrieve, update or delete post
    """
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    serializer_class = MainSerializer
    
    def get_queryset(self):
        group_pk = self.kwargs['boilerplate']
        #print(group_pk)
        queryset_main= Main.objects.filter(boilerplate_of_main = group_pk)
        return queryset_main

    #Custom actions when PUT
    def perform_update(self, serializer):
        instance = serializer.validated_data
        #add data in thn Model BoilerplateData
        es_instance = instance['sys_fun_inter'].rsplit(':', 1)
        ev_instance =instance['verb'].rsplit(' : ', 1)
        eo_instance = instance['flow_function_interface_item_system_state_stateset'].rsplit(':', 1)
        stateitem_instance, statevalue_instance,quantifier_instance,numunit_instance, stsysconset_instance  = [[""], [""], [""], [""], [""]]
        numinstance=''
        if instance['state_item_before_verb']:
            stateitem_instance = instance['state_item_before_verb'].rsplit(':', 1)
        if instance['statevalue_before_verb']:
            statevalue_instance = instance['statevalue_before_verb'].rsplit(':', 1)
        if instance['quantifier']:
            quantifier_instance = instance['quantifier'].rsplit(':', 1)
        if instance['mumerical_units']:
            numunit_instance = instance['mumerical_units'].rsplit(':', 1)
        if instance['statevalue_system_connection_stateset']:
            stsysconset_instance = instance['statevalue_system_connection_stateset'].rsplit(':', 1)
        if instance['numerical']:
            numinstance= instance['numerical']
        mn = (es_instance[len(es_instance)-1] + ' ' + stateitem_instance[len(stateitem_instance)-1] + ' ' + statevalue_instance[len(statevalue_instance)-1] + ' ' + instance['shall'] + ' ' + ev_instance[len(ev_instance)-1] + ' ' + quantifier_instance[len(quantifier_instance)-1] +' '+numinstance +' ' + numunit_instance[len(numunit_instance)-1]  + ' ' + eo_instance[len(eo_instance)-1] + ' ' + stsysconset_instance[len(stsysconset_instance)-1])
        boildata = BoilerplateData.objects.filter(owner_data=instance['boilerplate_of_main'].owner, boilerplate_data_id = instance['boilerplate_of_main'])
        #get instances of the ontology that this boilerplate belongs
        data = BoilerplateGroupClassesInstances.objects.filter(classes_instances_owner= instance['boilerplate_of_main'].owner, classes_instances_group_of_boilerplate = boildata.values('group_of_boilerplate_data')[0]['group_of_boilerplate_data'])
        sub_data = data.values('system_choices')[0]['system_choices'] + data.values('function_choices')[0]['function_choices'] + data.values('inteface_choices')[0]['inteface_choices']
        if( instance['sys_fun_inter'] not in sub_data):
            raise APIException("MAIN : Instance of Subject does not exist")
        stateitem_data = data.values('state_choices')[0]['state_choices'] + data.values('item_choices')[0]['item_choices']
        if( instance['state_item_before_verb'] not in stateitem_data):
            raise APIException("MAIN : Instance of State or Item before Verb does not exist")
        statevalue_data = data.values('state_value_choices')[0]['state_value_choices']
        if( instance['statevalue_before_verb'] not in statevalue_data):
            raise APIException("MAIN : Instance of StateValue before Verb does not exist")
        verb_data = data.values('main_verb_choices')[0]['main_verb_choices']
        if( instance['verb'] not in verb_data):
            raise APIException("MAIN : Instance of Verb does not exist")
        quantifier_data = data.values('quantifier_choices')[0]['quantifier_choices']
        if( instance['quantifier'] not in quantifier_data):
            raise APIException("MAIN : Instance of Quantifier does not exist")
        fifuintsysstatset_data =  data.values('system_choices')[0]['system_choices'] + data.values('function_choices')[0]['function_choices'] + data.values('flow_choices')[0]['flow_choices']  + data.values('inteface_choices')[0]['inteface_choices'] + data.values('item_choices')[0]['item_choices'] + data.values('state_choices')[0]['state_choices'] + data.values('state_set_choices')[0]['state_set_choices']
        if( instance['flow_function_interface_item_system_state_stateset'] not in fifuintsysstatset_data):
            raise APIException("MAIN : Instance of Object does not exist")
        stsysconset_data = data.values('system_choices')[0]['system_choices'] + data.values('state_set_choices')[0]['state_set_choices'] + data.values('connection_choices')[0]['connection_choices'] + data.values('state_value_choices')[0]['state_value_choices']
        if( instance['statevalue_system_connection_stateset'] not in stsysconset_data):
            raise APIException("MAIN : Instance of after Object does not exist")
        numunit_data = data.values('number_unit_choices')[0]['number_unit_choices']
        if( instance['mumerical_units'] not in numunit_data):
            raise APIException("MAIN : Instance of Number Unit does not exist")
        ontology_file = data.values('ontology_file')[0]['ontology_file']
        curmain_choices = inference.getclassofmain(instance, ontology_file)
        if(curmain_choices==None):
            raise APIException("Main choices not in [M1-M16]")
        if (curmain_choices[0] == 'ERROR'):
            raise APIException("Main choices not in [M1-M16]")
        else:
            boildata.update(main_data = mn )
            instance = serializer.save(main_choices = curmain_choices[0])
        #instance = serializer.save()



    #Custom actions when DELETE
    def perform_destroy(self, instance):
        #instance = serializer.validated_data
        

        instance.delete()

class MainChoicesViewSet(ListAPIView):
    """
    API view to retrieve, update or delete
    """
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = BoilerplateGroupClassesInstancesSerializer

    def get_queryset(self):
        group_pk = self.kwargs['groupboil']
        queryset_cl= BoilerplateGroupClassesInstances.objects.filter(classes_instances_group_of_boilerplate = group_pk)
        return queryset_cl


class SearchinOntologyAPIView(APIView):
    def get(self, request, instance, groupboil, format=None):
        data = BoilerplateGroupClassesInstances.objects.filter(classes_instances_group_of_boilerplate = groupboil)
        g = Graph()
        g.load(data.values('ontology_file')[0]['ontology_file'], format="turtle")
        data = (self.getClassontology(g, instance))
        return HttpResponse(data)


    def getClassontology(self, g, instance):
        info = []
        for ns_prefix, namespace in g.namespaces():
            for s, p, o in g.triples((URIRef( namespace+ instance.strip() ) ,None, None)):
                info = []
                for s1, p1, o1 in g.triples((URIRef( namespace+ instance.strip() ) ,None, None)):
                    sub=str(s1).split("#")
                    ver=str(p1).split("#")
                    obj=str(o1).split("#")
                    if(len(sub)>1 and  len(ver)>1 and len(obj)>1):
                        info.append('<li> <i>'+sub[1]+'</i> <u>'+ ver[1]+'</u> <i>'+obj[1]+'</i> </li>')
                for s2, p2, o2 in g.triples((None ,None, URIRef( namespace+ instance.strip()) )):
                    sub2=str(s2).split("#")
                    ver2=str(p2).split("#")
                    obj2=str(o2).split("#")
                    if(len(sub2)>1 and  len(ver2)>1 and len(obj2)>1):
                        info.append('<li> <i>'+sub2[1]+'</i> <u>'+ ver2[1]+'</u> <i>'+obj2[1]+'</i> </li>')
        if (len(info) > 0):
            return info
        else:
            raise APIException("There is no Class in the Ontology")



class MainChoicesAPIView(APIView):
    def get(self, request, groupboil, instance, comment, format=None):
        data = BoilerplateGroupClassesInstances.objects.filter(classes_instances_group_of_boilerplate = groupboil)
        Dictdata = BoilerplateGroupDictionary.objects.filter(classes_instances_group_of_boilerplate_dic = groupboil)
        
        g = Graph()
        g.load(data.values('ontology_file')[0]['ontology_file'], format="turtle")
        #onotlogy_prefix=self.getontologyfile(g)
        es_instance = instance.rsplit(':')
        #print(Dictdata.values('Dictionary_Data')[0]['Dictionary_Data'])
        try:
            class_prefix = self.getClassontologyfile(g,es_instance)
        except:
            raise APIException("Cannot find class of instance")
        for s, p, o in g.triples((URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#") + es_instance[len(es_instance)-1].strip() , RDF.type, URIRef(class_prefix))):
            raise APIException("This instance already exist")
        try:
            g.add(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , RDF.type, URIRef(class_prefix) ))
            g.add(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , RDFS.comment , Literal(comment) ))
            g.serialize(data.values('ontology_file')[0]['ontology_file'], format='turtle')
        except:
            raise APIException("Cannot Add instance")
        tempDict = []
        flag = 0
        #Add instance to Dictrionary
        for sao in Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']:
            if sao['Name'] == es_instance[0].strip():
                for sao2 in sao['TheClasses']:
                    if sao2['Class'] == es_instance[1].strip():
                        flag = 1
                        for sao3 in sao2['Subclass']:
                            if sao3['SubClass_name'] == es_instance[2].strip():
                                flag = 2
                                for sao4 in sao3['SubSubClass']:
                                    if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip():
                                        flag =3 
                                        for sao5 in sao4['SubSubClass']:
                                            if es_instance[4] and sao5['SubSubClass_name'] == es_instance[4].strip():
                                              flag =4
                                              for sao6 in sao5['SubSubClass']:
                                                if es_instance[5] and sao6['SubSubClass_name'] == es_instance[5].strip():
                                                    flag = 5
                                                    if(flag == 5):
                                                        if(sao6 ['SubInstanceOfSubclass'] == ''):
                                                            sao6 ['SubInstanceOfSubclass'] = []
                                                            sao6['SubInstanceOfSubclass'].append({"Instance": es_instance[6].strip(), "Comment": comment })
                                                        else:
                                                            sao6['SubInstanceOfSubclass'].append({"Instance": es_instance[6].strip(), "Comment": comment })
                                                            break
                                                if(flag == 4):
                                                    #print(instance, "Instance", es_instance[5].strip(), "Comment", comment )
                                                    if(sao5 ['SubInstanceOfSubclass'] == ''):
                                                        sao5 ['SubInstanceOfSubclass'] = []
                                                        sao5['SubInstanceOfSubclass'].append({"Instance": es_instance[5].strip(), "Comment": comment })
                                                    else:
                                                        sao5['SubInstanceOfSubclass'].append({"Instance": es_instance[5].strip(), "Comment": comment })
                                                    break
                                    if(flag == 3):
                                        #print(instance, "Instance", es_instance[4].strip(), "Comment", comment )
                                        if(sao4 ['SubInstanceOfSubclass'] == ''):
                                            sao4 ['SubInstanceOfSubclass'] = []
                                            sao4['SubInstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment })
                                        else:
                                            sao4['SubInstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment })
                                        break
                                    # SubSubClass_name
                                if(flag == 2):
                                    if(sao3 ['InstanceOfSubclass'] == ''):
                                        sao3 ['InstanceOfSubclass'] = []
                                        sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment })
                                    else:
                                        sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment })
                                    break
                        if (flag == 1):
                            if(sao2 ['Instance_of_Class'] == ''):
                                sao2 ['Instance_of_Class'] = []
                                sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment })
                            else:
                                sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment })
                            break
                if(flag==0):
                    sao['GeneralInstances'].append({"Instance": es_instance[1].strip(), "Comment": comment })
            tempDict.append(sao)
        Dictdata.update(Dictionary_Data= tempDict)
        if(len(es_instance) == 2):
            instance=es_instance[0] +': ' + instance 
        if (es_instance[0].strip() == 'System'):
            m = data.values('system_choices')[0]['system_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(system_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'Function'):
            m = data.values('function_choices')[0]['function_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(function_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'Item'):
            m = data.values('item_choices')[0]['item_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(item_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'Interface'):
            m = data.values('inteface_choices')[0]['inteface_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(inteface_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'Flow'):
            m = data.values('flow_choices')[0]['flow_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(flow_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'State'):
            m = data.values('state_choices')[0]['state_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(state_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'StateSet'):
            m = data.values('state_set_choices')[0]['state_set_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(state_set_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'StateValue'):
            m = data.values('state_value_choices')[0]['state_value_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(state_value_choices = str(m))
            return HttpResponse('Update Instance')
        if (es_instance[0].strip() == 'Connection'):
            m = data.values('connection_choices')[0]['connection_choices'][:-1]
            if (len(m) ==1 ):
                m+= '["'+instance+'","'+instance+'"]'+']'
            else :
                m+= ',["'+instance+'","'+instance+'"]'+']'
            data.update(connection_choices = str(m))
            return HttpResponse('Update Instance')
    def getontologyfile(self, g):
        for ns_prefix, namespace in g.namespaces():
            if ('DSO' in namespace and 'instance' in namespace):
                return namespace
        raise APIException("There is no file for instances")
    
    def getClassontologyfile(self, g, es_instance):
        if(len(es_instance) == 2 ):
            for ns_prefix, namespace in g.namespaces():
                for s, p, o in g.triples((URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
                    return URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() )
            raise APIException("There is no Class in the Ontology ")
        else:
            for ns_prefix, namespace in g.namespaces():
                for s, p, o in g.triples((URIRef( namespace+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
                    return URIRef( namespace+ es_instance[len(es_instance)-2].strip() )
            raise APIException("There is no Class in the Ontology ")


class DeleteMainChoicesAPIView(APIView):
    def get(self, request, groupboil, instance, comment, format=None):
        data = BoilerplateGroupClassesInstances.objects.filter(classes_instances_group_of_boilerplate = groupboil)
        Dictdata = BoilerplateGroupDictionary.objects.filter(classes_instances_group_of_boilerplate_dic = groupboil)
        
        g = Graph()
        g.load(data.values('ontology_file')[0]['ontology_file'], format="turtle")
        #onotlogy_prefix=self.getontologyfile(g)
        es_instance = instance.rsplit(':')
        #print(Dictdata.values('Dictionary_Data')[0]['Dictionary_Data'])
        exist = 0
        class_prefix = self.getClassontologyfile(g,es_instance)
        for s, p, o in g.triples((URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#") + es_instance[len(es_instance)-1].strip() , RDF.type, URIRef(class_prefix))):
            exist =1
        if( exist ==0 ):
            raise APIException("This instance cannot be deleted or it not exists")
        try:
            g.remove(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , None, None ))
            g.remove(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , RDFS.comment , None))
            g.serialize(data.values('ontology_file')[0]['ontology_file'], format='turtle')
        except:
            raise APIException("Cannot delete instance")
        tempDict = []
        flag = 0
        #Add instance to Dictrionary
        for sao in Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']:
            if sao['Name'] == es_instance[0].strip():
                for sao2 in sao['TheClasses']:
                    if sao2['Class'] == es_instance[1].strip():
                        flag = 1
                        for sao3 in sao2['Subclass']:
                            if sao3['SubClass_name'] == es_instance[2].strip():
                                flag = 2
                                for sao4 in sao3['SubSubClass']:
                                    if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip():
                                        flag =3 
                                        for sao5 in sao4['SubSubClass']:
                                            if es_instance[4] and sao5['SubSubClass_name'] == es_instance[4].strip():
                                              flag =4
                                              for sao6 in sao5['SubSubClass']:
                                                if es_instance[5] and sao6['SubSubClass_name'] == es_instance[5].strip():
                                                    flag = 5
                                                    if(flag == 5):
                                                        sao6['SubInstanceOfSubclass'].remove({"Instance": es_instance[6].strip(), "Comment": comment })
                                              if(flag == 4):
                                                sao5['SubInstanceOfSubclass'].remove({"Instance": es_instance[5].strip(), "Comment": comment })
                                    if(flag == 3):
                                        sao4['SubInstanceOfSubclass'].remove({"Instance": es_instance[4].strip(), "Comment": comment })
                                    # SubSubClass_name
                                if(flag == 2):
                                    sao3['InstanceOfSubclass'].remove({"Instance": es_instance[3].strip(), "Comment": comment })
                        if (flag == 1):
                            sao2 ['Instance_of_Class'].remove({"Instance": es_instance[2].strip(), "Comment": comment })
                if(flag==0):
                    sao['GeneralInstances'].remove({"Instance": es_instance[1].strip(), "Comment": comment })
            tempDict.append(sao)
        Dictdata.update(Dictionary_Data= tempDict)
        if(len(es_instance) == 2):
            instance=es_instance[0] +': ' + instance 
        if (es_instance[0].strip() == 'System'):
            m = data.values('system_choices')[0]['system_choices']
            if (instance in m) :
                m = m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(system_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'Function'):
            m = data.values('function_choices')[0]['function_choices']
            if (instance in m) :
                m = m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(function_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'Item'):
            m = data.values('item_choices')[0]['item_choices']
            if (instance in m) :
                m = m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(item_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'Interface'):
            m = data.values('inteface_choices')[0]['inteface_choices']
            if (instance in m) :
                m= m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(inteface_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'Flow'):
            m = data.values('flow_choices')[0]['flow_choices']
            if (instance in m) :
                m= m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(flow_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'State'):
            m = data.values('state_choices')[0]['state_choices']
            if (instance in m) :
                m= m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(state_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'StateSet'):
            m = data.values('state_set_choices')[0]['state_set_choices']
            if (instance in m) :
                m= m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(state_set_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'StateValue'):
            m = data.values('state_value_choices')[0]['state_value_choices']
            if (instance in m) :
                m= m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(state_value_choices = str(m))
            return HttpResponse('Instance deleted')
        if (es_instance[0].strip() == 'Connection'):
            m = data.values('connection_choices')[0]['connection_choices']
            if (instance in m) :
                m= m.replace(',["'+instance+'","'+instance+'"]', '')
            data.update(connection_choices = str(m))
            return HttpResponse('Instance deleted')


        


    def getontologyfile(self, g):
        for ns_prefix, namespace in g.namespaces():
            if ('DSO' in namespace and 'instance' in namespace):
                return namespace
        raise APIException("There is no file for instances")
    
    def getClassontologyfile(self, g, es_instance):
        if(len(es_instance) == 2 ):
            for ns_prefix, namespace in g.namespaces():
                for s, p, o in g.triples((URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
                    return URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() )
            raise APIException("There is no Class in the Ontology ")
        else:
            for ns_prefix, namespace in g.namespaces():
                for s, p, o in g.triples((URIRef( namespace+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
                    return URIRef( namespace+ es_instance[len(es_instance)-2].strip() )
            raise APIException("There is no Class in the Ontology ")





        
class ShallChoicesViewSet(APIView):

    def get(self, request):
        response = Response(SHALL_CHOICES)
        return response


class DictionaryViewSet(ListAPIView):
    """
    API view to retrieve list of Sections, Classes, Subclasses, Instances
    """
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = BoilerplateGroupDictionarySerializer

    def get_queryset(self):
        group_pk = self.kwargs['groupboil']
        queryset_cl= BoilerplateGroupDictionary.objects.filter(classes_instances_group_of_boilerplate_dic = group_pk)
        return queryset_cl

class MainSyntaxViewSet(APIView):
    serializer_class = BoilerplateGroupClassesInstances

    def get(self, request, groupboil, format=None):
        data = BoilerplateGroupClassesInstances.objects.filter(classes_instances_group_of_boilerplate = groupboil)
        g = Graph()
        g.load(data.values('ontology_file')[0]['ontology_file'], format="turtle")
        MAIN_SYNTAX = get_main_sytax(g)
        response = Response(MAIN_SYNTAX)
        return response




'''       #remove requirement if exists in the ontology
        g = Graph()
        g.load(data.values('ontology_file')[0]['ontology_file'], format="turtle")
        rdo_instance= URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + boildata.values('title_data')[0]['title_data'])
        g.remove((rdo_instance, None, None))
        g.remove((None, None, rdo_instance))
        main = Main.objects.filter(boilerplate_of_main = instance['boilerplate_of_main'])
        rdo_instance= URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + boildata.values('title_data')[0]['title_data'] +'_'+ main.values('main_choices')[0]['main_choices'])
        g.remove((rdo_instance, None, None))
        g.remove((None, None, rdo_instance))
        g.serialize(data.values('ontology_file')[0]['ontology_file'], format='turtle')
        #'''