from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils import timezone

from django.utils.text import slugify

class CareerManager(models.Manager):
    def active(self, *args, **kwargs):
        return super(CareerManager, self).filter(draft = False).filter(published_at__lte = timezone.now())

@python_2_unicode_compatible
class Career(models.Model):

    FULLTIME = 'Full-time'
    PARTTIME = 'Part-time'
    INTERNSHIP = 'Internship'
    RESEARCH = 'Research'

    ROLE_CATEGORY_CHOICES = (
        (FULLTIME, 'Full-time'),
        (PARTTIME, 'Part-time'),
        (INTERNSHIP, 'Internship'),
        (RESEARCH, 'Research'),
    )
    role_category = models.CharField(
        max_length=12,
        choices=ROLE_CATEGORY_CHOICES,
        default=FULLTIME,
    )

    # Role
    role = models.CharField(max_length = 120)

    # Location
    city = models.CharField(max_length=255)

    # Plain text and urlify slug
    career_slug = models.SlugField(unique = True)
    career_offer_title = models.CharField(max_length=255, default="")
    career_offer_description = models.TextField(default="")

    career_experience = models.TextField(default="")
    career_terms = models.TextField(default="")

    # Time and meta staff
    draft = models.BooleanField(default = False)
    published_at = models.DateField(auto_now = False, auto_now_add = False)
    updated = models.DateTimeField(auto_now = True, auto_now_add = False)
    timestamp = models.DateTimeField(auto_now = False, auto_now_add = True)

    objects = CareerManager()

    def __unicode__(self):
        return self.role

    def __str__(self):
        return self.role

    def get_absolute_url(self):
        return reverse('careers:detail', kwargs = {'slug':self.career_slug})

    class Meta:
        ordering = ["-timestamp", "-updated"]


def create_slug(instance, new_slug = None):
    career_slug =  slugify(instance.title)
    if new_slug is not None:
        career_slug = new_slug

    qs = Career.objects.filter(career_slug = career_slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" %(career_slug, qs.first().id)
        return create_slug(instance, slug = new_slug)
    return career_slug

def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.career_slug:
        instance.career_slug = create_slug(instance)

pre_save.connect(pre_save_post_receiver, sender = Career)
