# Path: horarios/serializers.py
# class SessionSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Session
# 
# class SubjectSimpleSerializer(serializers.ModelSerializer):
#     class Meta:
#         model =  Subject
#         fields = ('name','code')
# 
# class SubjectSerializer(serializers.ModelSerializer):
#     groups = GroupSerializer(many=True, read_only=True)
#     class Meta:
#         model =  Subject
# 
# class GroupSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Group
#     def to_representation(self, group):
#         return {
#             "id": group.id,
#             "teacher": group.teacher.name,
#             "schedule": json.loads(group.schedule),
#             "code": group.code,
#             "subject": group.subject.code,
#             "professions": [p.code for p in group.professions.all()]
#         }
# 
# class ProfessionSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Profession
# 
# Path: horarios/models.py
# class Session(models.Model):
#     url  = models.CharField(primary_key=True, max_length=10, default=make_uuid)
#     session = models.CharField(max_length=500000)
# 
# class Subject(models.Model):
#     name = models.CharField(max_length=200)
#     code = models.IntegerField(primary_key=True)
#     credits = models.IntegerField()
#     stype = models.CharField(max_length=10)
#     @staticmethod
#     def autocomplete(search_term="", profession="", subject_type=[]):
#         print "Search"
#         print search_term
#         print "profession"
#         print profession == ""
#         print "stype"
#         print subject_type
#         if search_term == "":
#             if profession == "":
#                 return Subject.objects.all()
#             else:
#                 query = Subject.objects.filter(
#                     groups__in=Group.objects.filter(professions__code=profession))
#                 if len(subject_type) != 0:
#                     query = query.filter(stype__in=subject_type)
#                 return query.distinct()
#         else:
#             search_term = sanitize_search_term(search_term)
#             query = Subject.objects.extra(
#                     where=["name @@ to_tsquery('sp', %s)"], params=[search_term])
#             if profession != "":
#                 query = query.filter(groups__in=Group.objects.filter(professions__code=profession))
#             if len(subject_type) != 0:
#                 query = query.filter(stype__in=subject_type)
#             return query.distinct()
# 
# class Group(models.Model):
#     schedule = models.CommaSeparatedIntegerField(max_length=100)
#     code = models.IntegerField()
#     teacher = models.ForeignKey(Teacher, related_name='groups')
#     subject = models.ForeignKey(Subject, related_name='groups')
#     professions = models.ManyToManyField(Profession)
# 
# class Profession(models.Model):
#     name = models.CharField(max_length=100)
#     code = models.CharField(primary_key=True, max_length=20)


from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from horarios.serializers import SessionSerializer, SubjectSimpleSerializer, SubjectSerializer, GroupSerializer, ProfessionSerializer
from horarios.models import Session, Subject, Group, Profession
from rest_framework import generics
from rest_framework.permissions import IsAdminUser, AllowAny
    from django.http import HttpResponse, Http404
    from django.conf import settings
    import json
    import subprocess
        import json
        DEPLOY_SCRIPT = getattr(settings,"DEPLOY_SCRIPT", "pwd")
        out = subprocess.check_output(settings.DEPLOY_SCRIPT)
        if not getattr(settings,"DEBUG",False):
            out = ""
        out_json = {'status' : 'success', 'output' : out }

    return HttpResponse(json.dumps(out_json), content_type='application/json')

class SubjectProfessionAutocompleteView(APIView):
    def get(self, request, *args , **kw):
        search_term = kw['search_term']
        try:
            profession  = int(kw['profession'])
        except:
            profession = ""
        try:
            subject_type = json.loads(kw['subject_type'])
        except:
            subject_type = []
        queryset = Subject.autocomplete(search_term,profession,subject_type)
        print queryset
        serializer = SubjectSimpleSerializer(queryset, many=True)
        return Response(serializer.data)

class SessionList(generics.ListCreateAPIView):
    queryset = Session.objects.all()
    serializer_class = SessionSerializer

class SessionDetail(generics.RetrieveUpdateAPIView):
    permission_classes = (AllowAny,)

# Path: horarios/serializers.py
# class SessionSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Session
# 
# class SubjectSimpleSerializer(serializers.ModelSerializer):
#     class Meta:
#         model =  Subject
#         fields = ('name','code')
# 
# class SubjectSerializer(serializers.ModelSerializer):
#     groups = GroupSerializer(many=True, read_only=True)
#     class Meta:
#         model =  Subject
# 
# class GroupSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Group
#     def to_representation(self, group):
#         return {
#             "id": group.id,
#             "teacher": group.teacher.name,
#             "schedule": json.loads(group.schedule),
#             "code": group.code,
#             "subject": group.subject.code,
#             "professions": [p.code for p in group.professions.all()]
#         }
# 
# class ProfessionSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Profession
# 
# Path: horarios/models.py
# class Session(models.Model):
#     url  = models.CharField(primary_key=True, max_length=10, default=make_uuid)
#     session = models.CharField(max_length=500000)
# 
# class Subject(models.Model):
#     name = models.CharField(max_length=200)
#     code = models.IntegerField(primary_key=True)
#     credits = models.IntegerField()
#     stype = models.CharField(max_length=10)
#     @staticmethod
#     def autocomplete(search_term="", profession="", subject_type=[]):
#         print "Search"
#         print search_term
#         print "profession"
#         print profession == ""
#         print "stype"
#         print subject_type
#         if search_term == "":
#             if profession == "":
#                 return Subject.objects.all()
#             else:
#                 query = Subject.objects.filter(
#                     groups__in=Group.objects.filter(professions__code=profession))
#                 if len(subject_type) != 0:
#                     query = query.filter(stype__in=subject_type)
#                 return query.distinct()
#         else:
#             search_term = sanitize_search_term(search_term)
#             query = Subject.objects.extra(
#                     where=["name @@ to_tsquery('sp', %s)"], params=[search_term])
#             if profession != "":
#                 query = query.filter(groups__in=Group.objects.filter(professions__code=profession))
#             if len(subject_type) != 0:
#                 query = query.filter(stype__in=subject_type)
#             return query.distinct()
# 
# class Group(models.Model):
#     schedule = models.CommaSeparatedIntegerField(max_length=100)
#     code = models.IntegerField()
#     teacher = models.ForeignKey(Teacher, related_name='groups')
#     subject = models.ForeignKey(Subject, related_name='groups')
#     professions = models.ManyToManyField(Profession)
# 
# class Profession(models.Model):
#     name = models.CharField(max_length=100)
#     code = models.CharField(primary_key=True, max_length=20)


# Path: horarios/views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from horarios.serializers import SessionSerializer, SubjectSimpleSerializer, SubjectSerializer, GroupSerializer, ProfessionSerializer
from horarios.models import Session, Subject, Group, Profession
from rest_framework import generics
from rest_framework.permissions import IsAdminUser, AllowAny
    from django.http import HttpResponse, Http404
    from django.conf import settings
    import json
    import subprocess
        import json

        DEPLOY_SCRIPT = getattr(settings,"DEPLOY_SCRIPT", "pwd")
        out = subprocess.check_output(settings.DEPLOY_SCRIPT)
        if not getattr(settings,"DEBUG",False):
            out = ""
        out_json = {'status' : 'success', 'output' : out }

    return HttpResponse(json.dumps(out_json), content_type='application/json')

class SubjectProfessionAutocompleteView(APIView):
    def get(self, request, *args , **kw):
        search_term = kw['search_term']
        try:
            profession  = int(kw['profession'])
        except:
            profession = ""
        try:
            subject_type = json.loads(kw['subject_type'])
        except:
            subject_type = []
        queryset = Subject.autocomplete(search_term,profession,subject_type)
        print queryset
        serializer = SubjectSimpleSerializer(queryset, many=True)
        return Response(serializer.data)

class SessionList(generics.ListCreateAPIView):
    queryset = Session.objects.all()
    serializer_class = SessionSerializer

class SessionDetail(generics.RetrieveUpdateAPIView):
    permission_classes = (AllowAny,)

    queryset = Session.objects.all()