from django.db import models
from django.utils.translation import ugettext_lazy as _
from core.models import WinoseBaseWithTrackingModel
from django.core import validators

REF_GAS_TYPES = (('B', _('n-Butanol')),
                 ('H', _('H2S')),)


class ReferenceGas(WinoseBaseWithTrackingModel):
    class Meta:
        verbose_name_plural = _('reference gases')
        verbose_name = _('reference gas')

    overview_url = 'reference gases_list'
    detail_url = 'reference gas_detail'
    create_url = 'reference gas_create'
    update_url = 'reference gas_update'

    # some name for the cylinder
    name = models.CharField(
        max_length=63,
        verbose_name=_('name'),
        unique=True
    )

    # cylinder number
    number = models.CharField(
        max_length=63,
        verbose_name=_('number')
    )

    # optional expiration date
    expires_at = models.DateField(
        verbose_name=_('expires'),
        null=True,
        blank=True
    )

    substance = models.CharField(
        choices=REF_GAS_TYPES,
        max_length=1,
        default='B',
        verbose_name=_('substance')
    )

    concentration = models.FloatField(
        verbose_name=_('concentration'),
        validators=[validators.MinValueValidator(1.0)]
    )

    # random notes for this cylinder
    comment = models.TextField(
        max_length=1023,
        verbose_name=_('comments'),
        blank=True  # don't need to enter a comment
    )

    certificate = models.FileField(
        verbose_name=_('certificate'),
        upload_to='refgas_certs',
        blank=True
    )

    in_service_since = models.DateField(
        blank=True,
        null=True,
        verbose_name=_('in service since')
    )

    def __str__(self):
        return '{0} ({1})'.format(self.name, self.get_substance_display())

    @staticmethod
    def verbose_name_substance(substance_key):
        try:
            from django.utils.translation import force_text

            t = list(filter(lambda x: x[0] == substance_key, REF_GAS_TYPES))
            return force_text(t[0][1])
        except:
            return None
