import math
from datetime import datetime, timedelta

from django.db import models
from django.contrib.gis.db.models.fields import PointField, PolygonField, LineStringField
from django.contrib.gis.measure import D
from colorfield.fields import ColorField

class Marker(models.Model):
  timestamp = models.DateTimeField(unique=True)
  location = PointField(dim=2, srid=4326)
  alt = models.FloatField("Altitude")
  hdop = models.IntegerField(null=True, blank=True)
  speed = models.FloatField("Speed in km/h", null=True, blank=True)

  class Meta:
    ordering = ('timestamp',)

class Trip(models.Model):
  startTime = models.DateTimeField()
  endTime = models.DateTimeField()
  name = models.CharField(max_length=255)
  description = models.TextField(null=True, blank=True)
  totalTime = models.DurationField("Total duration", default=timedelta(0))
  center = PointField(dim=2, srid=4326, default=None)
  line = LineStringField(dim=2, srid=4326, default=None, null=True)

  color = ColorField()
  distance = models.FloatField("Distance in m", default=0)
  topSpeed = models.FloatField("Top speed in km/h", default=0)
  avgSpeed = models.FloatField("Average speed in km/h", default=0)
  ascendHeight = models.FloatField("Ascend height in m", default=0)
  descendHeight = models.FloatField("Descend height in m", default=0)
  movementTime = models.DurationField("Movement duration", default=timedelta(0))

  path = models.BinaryField("Path", default=bytes())

  class Meta:
    ordering = ('startTime',)


class CensoredLocation(models.Model):
  location = PointField(dim=2, srid=4326)
  radius = models.IntegerField(default=800)
  name = models.CharField(max_length=255)


def distance_to_decimal_degrees(distance, latitude):
    """
    Source of formulae information:
        1. https://en.wikipedia.org/wiki/Decimal_degrees
        2. http://www.movable-type.co.uk/scripts/latlong.html
    :param distance: an instance of `from django.contrib.gis.measure.Distance`
    :param latitude: y - coordinate of a point/location
    """
    lat_radians = latitude * (math.pi / 180)
    # 1 longitudinal degree at the equator equal 111,319.5m equiv to 111.32km
    return distance.m / (111_319.5 * math.cos(lat_radians))