# Path: webapp/api/serializers.py
# class UserSerializer(serializers.ModelSerializer):
#     appointment_set = AppointmentSerializer(many=True, read_only=True)
#     #location_set = LocationSerializer(many=True, read_only=True)
#     membership_set = MembershipSerializer(many=True, read_only=True)
#     #membership_set = serializers.RelationsList()
# 
#     class Meta:
#         model = User
#         fields = ('id', 'username', 'email', 'first_name', 'is_superuser', 'appointment_set', 'membership_set')
# 
# class LocationSerializer(serializers.ModelSerializer):
# 
#     class Meta:
#         model = Location
#         fields = ('name', 'type', 'latitude', 'longitude', 'organization',
#                   'direction1', 'direction1_label', 'direction2', 'direction2_label')
# 
# class AppointmentSerializer(serializers.ModelSerializer):
#     location = LocationSerializer()
# 
#     class Meta:
#         model = Appointment
#         ordering = ['actual_end']
#         fields = ('id', 'user', 'location', 'scheduled_start', 'actual_start', 'actual_end','status')


from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, LocationSerializer, AppointmentSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import detail_route  # action
from main.models import Organization, OrganizationMetrics, Location, Appointment, Survey, SurveyValue, Metric, Value, \
    Event, SurveyEvent
from main.logic import *
from django.http import JsonResponse
from main.views import RequestCSVView
import datetime
import json
                # If posted data is in expected metrics, save it
                if str(k).lower() in metrics:
                    metric = Metric.objects.get(system_name=k)
                    value = Value.objects.get(value_set=metric.value_set, stored_value=v)
                    sv, c = SurveyValue.objects.get_or_create(survey=survey, metric=metric, value=value)
                    print "Saving %s = %s" % (k, v)
            except Metric.DoesNotExist:
                print "Metric does not exist metric:sys_name=%s    value:stored_val=%s" % (k, v)
            except Value.DoesNotExist:
                print "Value does not exist metric:sys_name=%s     value:stored_val=%s" % (k, v)

        return Response(None, status=status.HTTP_200_OK)


    @detail_route(methods=['POST'])
    def event(self, request, pk=None):
        appt = self.get_object()
        for k, v in request.DATA.items():
            print "{} {}".format(k, v)
        ev = Event.objects.get(id=request.DATA['event_id'])
        guid = request.DATA['guid']
        se = SurveyEvent.objects.create(appointment=appt, event=ev, guid=guid)
        return Response(None, status=status.HTTP_200_OK)


class UserViewSet(viewsets.ModelViewSet):
    """s
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()

# Path: webapp/api/serializers.py
# class UserSerializer(serializers.ModelSerializer):
#     appointment_set = AppointmentSerializer(many=True, read_only=True)
#     #location_set = LocationSerializer(many=True, read_only=True)
#     membership_set = MembershipSerializer(many=True, read_only=True)
#     #membership_set = serializers.RelationsList()
# 
#     class Meta:
#         model = User
#         fields = ('id', 'username', 'email', 'first_name', 'is_superuser', 'appointment_set', 'membership_set')
# 
# class LocationSerializer(serializers.ModelSerializer):
# 
#     class Meta:
#         model = Location
#         fields = ('name', 'type', 'latitude', 'longitude', 'organization',
#                   'direction1', 'direction1_label', 'direction2', 'direction2_label')
# 
# class AppointmentSerializer(serializers.ModelSerializer):
#     location = LocationSerializer()
# 
#     class Meta:
#         model = Appointment
#         ordering = ['actual_end']
#         fields = ('id', 'user', 'location', 'scheduled_start', 'actual_start', 'actual_end','status')


# Path: webapp/api/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, LocationSerializer, AppointmentSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import detail_route  # action
from main.models import Organization, OrganizationMetrics, Location, Appointment, Survey, SurveyValue, Metric, Value, \
    Event, SurveyEvent
from main.logic import *
from django.http import JsonResponse
from main.views import RequestCSVView
import datetime
import json

                # If posted data is in expected metrics, save it
                if str(k).lower() in metrics:
                    metric = Metric.objects.get(system_name=k)
                    value = Value.objects.get(value_set=metric.value_set, stored_value=v)
                    sv, c = SurveyValue.objects.get_or_create(survey=survey, metric=metric, value=value)
                    print "Saving %s = %s" % (k, v)
            except Metric.DoesNotExist:
                print "Metric does not exist metric:sys_name=%s    value:stored_val=%s" % (k, v)
            except Value.DoesNotExist:
                print "Value does not exist metric:sys_name=%s     value:stored_val=%s" % (k, v)

        return Response(None, status=status.HTTP_200_OK)


    @detail_route(methods=['POST'])
    def event(self, request, pk=None):
        appt = self.get_object()
        for k, v in request.DATA.items():
            print "{} {}".format(k, v)
        ev = Event.objects.get(id=request.DATA['event_id'])
        guid = request.DATA['guid']
        se = SurveyEvent.objects.create(appointment=appt, event=ev, guid=guid)
        return Response(None, status=status.HTTP_200_OK)


class UserViewSet(viewsets.ModelViewSet):
    """s
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()

    serializer_class = UserSerializer