from django.db import models
from datetime import datetime
from utils import generate_validate_token

class Person(models.Model):
#Basic Info
  user = models.ForeignKey(User, blank=True, null=True, db_index=True)
  first_name = models.CharField(max_length=255)
  last_name = models.CharField(max_length=255)
  email = models.EmailField(blank=True, null=True, unique=True, db_index=True)
  email_validated = models.BooleanField(default=False)
  tel_no = models.CharField(max_length=100, blank=True)
  about = models.TextField(blank=True, null=True)

#Occupation info
  occupations = models.ManyToManyField("Occupation", through='PersonOccupation', blank=True, null=True)
  is_practitioner = models.BooleanField(default=False)
  is_enthusiast = models.BooleanField(default=True)
  
#Personal info
  dob = models.DateField(null=True, verbose_name="Date of Birth")
  gender = models.CharField(max_length=255, choices=GENDER_CHOICES, blank=True)
  image = models.ImageField(upload_to='images/', blank=True, null=True)
  locations = models.ManyToManyField("Location", blank=True, null=True)  
  
#Groups and Connections
  is_freelancer = models.BooleanField(default=False)
  groups = models.ManyToManyField("TheatreGroup", blank=True, null=True, through='PersonGroup')
  connections = models.ManyToManyField('Person', blank=True, null=True, through='PersonPerson')
  productions = models.ManyToManyField("Production", blank=True, null=True, through='PersonProduction')
#  trainings = models.ManyToManyField("Training", blank=True, null=True)
  photos = models.ManyToManyField("PhotoAlbum", blank=True, null=True)
#  orphans = models.ManyToManyField("Orphan", blank=True, null=True, through='PersonOrphan')

#Meta
  joined = models.DateTimeField(auto_now_add=True)
  last_modified = models.DateTimeField(auto_now=True)
  last_accessed = models.DateTimeField(default=datetime.now)

#Tokens
  reset_token = modes.CharField(max_length=256, null=True)
  validate_token = models.CharField(max_length=256, null=True, default=generate_validate_token)


  def __unicode__(self):
    return self.first_name + " " + self.last_name

  def is_orphan(self):
    return self.user == None



class Occupation(models.Model):
  name = models.CharField(max_length=255)
  parent = models.ForeignKey('Occupation', blank=True, null=True)

  def __unicode__(self):
    return self.name

  def is_child(self):
    return self.parent != None

  def is_parent(self):
    if self.is_child():
      return False
    else:
      if Occupation.objects.filter(parent=self).count() > 0: #self has children
        return True
    return False


class PersonOccupation(models.Model):
  person = models.ForeignKey(Person, db_index=True)
  occupation = models.ForeignKey(Occupation)
  order = models.IntegerField()



# Create your models here.
