# Path: beacon/models.py
# class DetectorDevice(models.Model):
#     """ device which detects beacons, now only cellphones """
#     externalId = models.CharField(max_length=32, unique=True)
# 
#     def getDict(self):
#         dict = {}
#         dict['deviceId'] = self.externalId
#         return dict
# 
#     def __str__(self):
#         return self.externalId
# 
# class Beacon(models.Model):
#     macAddr = models.CharField(max_length=20, unique=True)
#     uuid    = models.UUIDField(editable=False)
#     major   = models.CharField(max_length=10, null=False)
#     minor   = models.CharField(max_length=10, null=False)
# 
#     def getDict(self):
#         dict = {}
#         dict['macAddr'] = self.macAddr
#         dict['uuid'] = str(self.uuid)
#         dict['major'] = self.major
#         dict['minor'] = self.minor
#         return dict
# 
#     class Meta:
#         unique_together = ('uuid', 'major', 'minor')
# 
# class BeaconLog(models.Model):
#     time         = models.DateTimeField(null=False)
#     rssi         = models.IntegerField(null=False)
#     measurePower = models.IntegerField(null=False)
#     beacon       = models.ForeignKey(Beacon, on_delete=models.CASCADE)
#     device       = models.ForeignKey(DetectorDevice, on_delete=models.CASCADE)
# 
#     def __str__(self):
#         return "time: {} | rssi: {} | measurePower: {}".format(
#                 self.time, self.rssi, self.measurePower)
# 
#     def getDict(self):
#         dict = {}
#         dict['time'] = formatDateTime(self.time)
#         dict['rssi'] = self.rssi
#         dict['measurePower'] = self.measurePower
#         return dict
# 
# class Event(models.Model):
#     time   = models.DateTimeField(null=False)
#     event  = models.TextField(null=False)
#     device = models.ForeignKey(DetectorDevice, on_delete=models.CASCADE)
# 
#     def getDict(self):
#         dict = {}
#         dict['time']  = formatDateTime(self.time)
#         dict['event'] = self.event
#         return dict


from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.db import connection
from django.db.models.query import Prefetch
from django.utils import timezone, dateparse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from beacon.models import DetectorDevice, Beacon, BeaconLog, Event
import json
        return super(SaveData, self).dispatch(request, *args, **kwargs)

    def post(self, request):
  
        jsonEncoded = request.POST['data']
        jsonDecoded = json.loads(jsonEncoded)
        
        deviceId = jsonDecoded['DeviceID']
        beacons  = jsonDecoded['MeasureData']['Beacons']
        events   = jsonDecoded['MeasureData']['Events']

        if DetectorDevice.objects.filter(externalId=deviceId).exists():
            device = DetectorDevice.objects.get(externalId=deviceId)
        else:
            device = DetectorDevice.objects.create(externalId=deviceId)

        for beacon in beacons:
            if Beacon.objects.filter(macAddr=beacon['Mac Address']).exists():
                beaconObj = Beacon.objects.get(macAddr=beacon['Mac Address'])
            else:
                beaconObj = Beacon.objects.create(
                    macAddr=beacon['Mac Address'],
                    uuid=beacon['UUID'],
                    major=beacon['Major'],
                    minor=beacon['Minor']
                    )

            for record in beacon['Log']:
                time = dateparse.parse_datetime(record['Time'])
                time = timezone.make_aware(time)

# Path: beacon/models.py
# class DetectorDevice(models.Model):
#     """ device which detects beacons, now only cellphones """
#     externalId = models.CharField(max_length=32, unique=True)
# 
#     def getDict(self):
#         dict = {}
#         dict['deviceId'] = self.externalId
#         return dict
# 
#     def __str__(self):
#         return self.externalId
# 
# class Beacon(models.Model):
#     macAddr = models.CharField(max_length=20, unique=True)
#     uuid    = models.UUIDField(editable=False)
#     major   = models.CharField(max_length=10, null=False)
#     minor   = models.CharField(max_length=10, null=False)
# 
#     def getDict(self):
#         dict = {}
#         dict['macAddr'] = self.macAddr
#         dict['uuid'] = str(self.uuid)
#         dict['major'] = self.major
#         dict['minor'] = self.minor
#         return dict
# 
#     class Meta:
#         unique_together = ('uuid', 'major', 'minor')
# 
# class BeaconLog(models.Model):
#     time         = models.DateTimeField(null=False)
#     rssi         = models.IntegerField(null=False)
#     measurePower = models.IntegerField(null=False)
#     beacon       = models.ForeignKey(Beacon, on_delete=models.CASCADE)
#     device       = models.ForeignKey(DetectorDevice, on_delete=models.CASCADE)
# 
#     def __str__(self):
#         return "time: {} | rssi: {} | measurePower: {}".format(
#                 self.time, self.rssi, self.measurePower)
# 
#     def getDict(self):
#         dict = {}
#         dict['time'] = formatDateTime(self.time)
#         dict['rssi'] = self.rssi
#         dict['measurePower'] = self.measurePower
#         return dict
# 
# class Event(models.Model):
#     time   = models.DateTimeField(null=False)
#     event  = models.TextField(null=False)
#     device = models.ForeignKey(DetectorDevice, on_delete=models.CASCADE)
# 
#     def getDict(self):
#         dict = {}
#         dict['time']  = formatDateTime(self.time)
#         dict['event'] = self.event
#         return dict


# Path: beacon/views.py
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.db import connection
from django.db.models.query import Prefetch
from django.utils import timezone, dateparse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from beacon.models import DetectorDevice, Beacon, BeaconLog, Event
import json

        return super(SaveData, self).dispatch(request, *args, **kwargs)

    def post(self, request):
  
        jsonEncoded = request.POST['data']
        jsonDecoded = json.loads(jsonEncoded)
        
        deviceId = jsonDecoded['DeviceID']
        beacons  = jsonDecoded['MeasureData']['Beacons']
        events   = jsonDecoded['MeasureData']['Events']

        if DetectorDevice.objects.filter(externalId=deviceId).exists():
            device = DetectorDevice.objects.get(externalId=deviceId)
        else:
            device = DetectorDevice.objects.create(externalId=deviceId)

        for beacon in beacons:
            if Beacon.objects.filter(macAddr=beacon['Mac Address']).exists():
                beaconObj = Beacon.objects.get(macAddr=beacon['Mac Address'])
            else:
                beaconObj = Beacon.objects.create(
                    macAddr=beacon['Mac Address'],
                    uuid=beacon['UUID'],
                    major=beacon['Major'],
                    minor=beacon['Minor']
                    )

            for record in beacon['Log']:
                time = dateparse.parse_datetime(record['Time'])
                time = timezone.make_aware(time)

                r = BeaconLog.objects.create(