from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.utils.translation import gettext_lazy

from console.models import NameDescriptionModel, UniqueNameDescriptionModel
from devices.enums import DeviceType, AdjustDatetime


class Device(NameDescriptionModel):
    type = models.CharField(choices=DeviceType.choices,
                            max_length=8)
    ip = models.GenericIPAddressField(unique=True,
                                      verbose_name=gettext_lazy('IP'),
                                      help_text=gettext_lazy('Device IP address'))
    port = models.IntegerField(verbose_name=gettext_lazy('Port'),
                               help_text=gettext_lazy("Input port number (UDP)"),
                               unique=True,
                               error_messages={
                                   'unique': gettext_lazy('This port is already in use')
                               },
                               validators=(MinValueValidator(1500),
                                           MaxValueValidator(65535)))
    adjust_datetime = models.IntegerField(choices=AdjustDatetime.choices,
                                          default=AdjustDatetime.LOCAL,
                                          verbose_name=gettext_lazy("Adjust datetime"))
    updated = models.DateTimeField(
        gettext_lazy('Updated'), help_text=gettext_lazy('Date and time of the last update'),
        auto_now=True
    )
    group = models.ForeignKey('DeviceGroup', related_name='devices', on_delete=models.SET_NULL, null=True, blank=True)


class DeviceGroup(UniqueNameDescriptionModel):
    pass


class DeviceConnectedMixin(models.Model):
    """ Add connection to device by name.

    Device can be ARMAIF or Endpoint
    """
    sensor = models.CharField(null=True, blank=True, max_length=128, verbose_name=gettext_lazy("Sensor name"))  # todo rename later

    class Meta:
        abstract = True
