from django.db import models
from django.utils.translation import ugettext_lazy as _

from core.models import PersonBase, AddressBase, ContactDataBase, WinoseBaseWithTrackingModel


class Panelist(PersonBase, AddressBase, ContactDataBase, WinoseBaseWithTrackingModel):
    class Meta:
        ordering = ['last_name']
        verbose_name = _('panelist')
        verbose_name_plural = _('panelists')

    overview_url = 'panelists_list'
    create_url = 'panelist_create'
    detail_url = 'panelist_detail'
    update_url = 'panelist_update'

    # the date of birth might be an interesting fact for a panelist
    date_of_birth = models.DateField(
        null=True,
        verbose_name=_('date of birth')
    )

    # free form comments
    comments = models.TextField(
        max_length=1023,
        verbose_name=_('comments'),
        blank=True
    )

    shorthand = models.CharField(
        max_length=10,
        unique=True,
        editable=False,
        verbose_name=_('Identifier')
    )

    qualified = models.BooleanField(
        null=False,
        default=False,
        verbose_name=_('qualified'),
        editable=False
    )

    def save(self, *args, **kwargs):
        if self.pk is None:
            # generate shorthand if user is new...
            self.shorthand = Panelist.generate_unique_shorthand(self.first_name, self.last_name)

        super(Panelist, self).save(*args, **kwargs)

    def __str__(self):
        return '{0} {1}'.format(self.first_name, self.last_name)

    @staticmethod
    def generate_shorthand(first_name, last_name):
        return last_name[0:min(2, len(last_name))] + first_name[0]

    @staticmethod
    def generate_unique_shorthand(first_name, last_name):
        shorthand_base = current_shorthand = Panelist.generate_shorthand(first_name, last_name)
        is_unique = False
        run_count = 0

        while not is_unique:
            try:
                Panelist.objects.get(shorthand=current_shorthand)
                current_shorthand = '{0}{1}'.format(shorthand_base, run_count)
                run_count += 1
            except Panelist.DoesNotExist:
                is_unique = True

        return current_shorthand
