import json
from datetime import datetime
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.core.serializers.json import DjangoJSONEncoder
from django.views import View
from django.core.cache import cache
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.gis.geos import Point

from .models import *

def index(request):
  return render(request, 'gps_logger/index.html')

@permission_required("gps-logger.markers.change")
def upload(request):
  return render(request, 'gps_logger/upload.html')

class MarkerCreateView(PermissionRequiredMixin, View):
  permission_required = ("gps-logger.markers.change")

  def post(self, request):
    insert_count = censor_count = replace_count = 0
    data = json.loads(request.body)
    for file in data:
      if len(data[file]) == 0:
        continue
      objects = [Marker(
          timestamp=datetime.strptime(x['timestamp'].replace("Z","-0000"), r"%Y-%m-%dT%H:%M:%S.%f%z"),
          location = Point(x['lng'], x['lat']),
          alt = x['alt'],
          hdop = x.get('hdop', None),
          speed = x.get('speed', None)
        ) for x in data[file]]
      start_date = objects[0].timestamp
      end_date = objects[-1].timestamp
      oldMarkers = Marker.objects.filter(timestamp__range=(start_date, end_date)).all()
      identical = len(oldMarkers) == len(objects)
    
      if identical:
        for i, marker in enumerate(oldMarkers):
          if marker.timestamp != objects[i].timestamp:
            identical = False
            break

      if identical:
        for i, marker in enumerate(oldMarkers):
          objects[i].id = marker.id
        Marker.objects.bulk_update(objects, ['location', 'alt', 'hdop', 'speed'])
        replace_count += len(oldMarkers)
      else:
        insert_count += len(objects) - len(oldMarkers)
        oldMarkers.delete()
        Marker.objects.bulk_create(objects)
    
    censor_count = censor()

    return JsonResponse({
        'censored': censor_count,
        'replaced': replace_count,
        'inserted': insert_count - censor_count
      }, status=201)

def marker_view(request):
  data = cache.get('markers')
  if not data:
    values = list(Marker.objects.values())
    for marker in values:
      location  = marker['location']
      if location:
        marker['lng'] = location.x
        marker['lat'] = location.y
      del marker['location']
    data = json.dumps(values, cls=DjangoJSONEncoder)
    cache.set('markers', data, 3600*24)
  return HttpResponse(data, content_type='application/json')

class DeleteCensoredView(PermissionRequiredMixin, View):
  permission_required = ("gps-logger.markers.change",)
  def get(self, request):
    counter = censor()
    return JsonResponse({'censored': counter})

def censor() -> int:
  counter = 0
  locations = CensoredLocation.objects.all()
  for location in locations:
    counter += location.delete_markers()
  if(cache.get('markers')):
    cache.delete('markers')
  return counter