import datetime

from django.core import validators
from django.db import models

MIN_SIGNAL = 0
MAX_SIGNAL = 100


# http://stackoverflow.com/questions/849142/how-to-limit-the-maximum-value-of-a-numeric-field-in-a-django-model/849426#849426
class IntegerRangeField(models.IntegerField):
  def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
    self.min_value, self.max_value = min_value, max_value
    models.IntegerField.__init__(self, verbose_name, name, **kwargs)
  def formfield(self, **kwargs):
    defaults = {'min_value': self.min_value, 'max_value':self.max_value}
    defaults.update(kwargs)
    return super(IntegerRangeField, self).formfield(**defaults)


class WirelessClient(models.Model):
  mac = models.CharField(max_length=17, unique=True)
  def __unicode__(self):
    return self.mac


class Organization(models.Model):
  fullname = models.CharField(max_length=100,unique=True)
  name = models.CharField(max_length=100,unique=True)
  def __unicode__(self):
    return self.fullname

  @staticmethod
  def get_name_by_ssid(ssid):
    """ Try to determine the organization via the SSID """
    ssid = ssid.lower()
    name = None
    if ssid.startswith('ap') and ssid.endswith('wleiden.net'):
      name = 'WirelessLeiden'
    elif ssid.startswith('il-') and ssid.endswith('wleiden.net'):
      name = 'WirelessLeiden'
    elif ssid.startswith('ap') and 'wirelessleiden' in ssid:
      name = 'WirelessLeiden'
    elif ssid.startswith('ap-') and 'westeinder' in ssid:
      name = 'WirelessPlassen'
    elif ssid.endswith('walphen.net'):
      name = 'WirelessAlphen'
    elif 'wirelessarnhem' in ssid:
      name = 'WirelessArnhem'
    return name

  @staticmethod
  def get_by_ssid(ssid):
    name = Organization.get_name_by_ssid(ssid)
    if not name:
      return None
    else:
      return Organization.objects.get(name=name)


class Node(models.Model):
  name = models.CharField(max_length=50, unique=True)
  latitude = models.FloatField(null=True,blank=True)
  longitude = models.FloatField(null=True,blank=True)
  organization = models.ForeignKey(Organization,null=True, blank=True)

  def __unicode__(self):
    return "%s - %s" % (self.name, self.organization)

class Accespoint(models.Model):
  mac = models.CharField(max_length=17)
  ssid = models.CharField(max_length=64)
  organization = models.ForeignKey(Organization,null=True, blank=True)
  encryptie = models.BooleanField()
  class Meta:
    unique_together = ('mac', 'ssid')
  def __unicode__(self):
    return "%s - %s" % (self.mac, self.ssid)


  def save(self, *args, **kwargs):
    self.organization = self.get_organization(self.ssid)
    super(Accespoint, self).save(*args, **kwargs)

class Gebruiker(models.Model):
  naam = models.CharField(max_length=64)
  email = models.CharField(max_length=64)
  def __unicode__(self):
    return "%s - %s" % (self.naam, self.email)

class Apparatuur(models.Model):
  antenne = models.CharField(max_length=64, default="onbekend")
  kaart = models.CharField(max_length=64, default="onbekend")
  def __unicode__(self):
    return "%s - %s" % (self.antenne, self.kaart)
  class Meta:
    verbose_name_plural = 'Apparatuur'
    unique_together = ('antenne', 'kaart')

class MeetRondje(models.Model):
  datum = models.DateTimeField(blank=True,null=True,default=datetime.datetime.now)
  naam = models.CharField(max_length=64)
  gebruiker = models.ForeignKey(Gebruiker)
  apparatuur = models.ForeignKey(Apparatuur)
  def __unicode__(self):
    return "%s - %s" % (self.gebruiker.naam, self.naam)
  class Meta:
    verbose_name_plural = 'MeetRondjes'

class MeetBestand(models.Model):
  meetrondje = models.ForeignKey(MeetRondje)
  bestand = models.FileField(upload_to='scan-data/%Y/%m/%d')
  is_imported = models.BooleanField(default=False)
  class Meta:
    verbose_name_plural = 'MeetBestanden'
    unique_together = ('meetrondje', 'bestand')
  def __unicode__(self):
    return "%s - %s" % (self.meetrondje, self.bestand)
  

class Meting(models.Model):
  meetrondje = models.ForeignKey(MeetRondje)
  accespoint = models.ForeignKey(Accespoint)
  latitude = models.FloatField()
  longitude = models.FloatField()
  signaal = IntegerRangeField(max_length=3,min_value=MIN_SIGNAL,max_value=MAX_SIGNAL)
  def __unicode__(self):
    return "%s @ %.5f,%.5f : %s" % (self.accespoint.ssid, float(self.latitude), float(self.longitude), self.signaal)
  class Meta:
    # This implies that you cannot have multiple messurements on the same
    # location for a single 'run', thus the data needs cleaned before to make
    # this properly hold.
    unique_together = ('meetrondje', 'accespoint', 'latitude', 'longitude'),
    verbose_name_plural = 'Metingen'

