from django.db import models
from app.models import ItfModel
from django.contrib.auth.models import User
from datetime import datetime
from django.contrib.localflavor.in_.forms import INZipCodeField
#from ox.django.fields import DictField
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from scriptbank.models import Script

GENDER_CHOICES = (
  ('M', 'Male'),
  ('F', 'Female'),
  ('O', 'Other'),
)


class Person(ItfModel):
    #ItfModel stuff:
    form_names = ['PersonForm', 'PopupPersonForm']
    fts_fields = ['first_name', 'last_name', 'email', 'about']
#Basic Info
    user = models.ForeignKey(User, blank=True, null=True, db_index=True, editable=False)
    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, editable=False) #s commented this out since its handled by allauth
    tel_no = models.CharField(max_length=100, blank=True)
    about = models.TextField(blank=True, null=True)
    dob = models.DateField(null=True, verbose_name="Date of Birth", blank=True)
    is_practitioner = models.BooleanField(default=False)
    is_enthusiast = models.BooleanField(default=True)
    is_freelancer = models.BooleanField(default=False) #Change to is_associate

#Occupation info
    occupations = models.ManyToManyField("Occupation", through='PersonOccupation', blank=True, null=True)
  
#Personal info
    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)  
    locations = generic.GenericRelation("Location") 
#Groups and Connections
    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, related_name="trainee")
#    awards = models.ManyToManyField("Award", blank=True, null=True)
    languages = models.ManyToManyField("Language", blank=True, null=True) #s added
    awards = generic.GenericRelation("Award")
    buzzitems = generic.GenericRelation("BuzzItem")
#   photos = models.ManyToManyField("PhotoAlbum", blank=True, null=True)
#   orphans = models.ManyToManyField("Orphan", blank=True, null=True, through='PersonOrphan')

#Meta
    last_accessed = models.DateTimeField(default=datetime.now)

#Tokens
#    reset_token = models.CharField(max_length=256, null=True, editable=False) #s remove these tokens from here
#    validate_token = models.CharField(max_length=256, null=True, editable=False)


    def __unicode__(self):
        return "%s %s" % (self.first_name, self.last_name,)
        
    def get_title(self):
        return self.__unicode__()

    def get_dict(self):
        return {
            'first_name': self.first_name,
            'last_name': self.last_name,
            'about': self.about
        }

OCCUPATION_TYPES = (
    ('practitioner', 'Practitioner'),
    ('associate', 'Associate'),
)

class Occupation(models.Model):
    name = models.CharField(max_length=255)
    occupation_type = models.CharField(choices=OCCUPATION_TYPES, max_length=64)
    extra_text = models.BooleanField(default=False)    

    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

BUZZ_ITEM_TYPES = (
    ('review', 'Review'),
    ('publicity', 'Publicity'),
)

class BuzzItem(ItfModel):
    link = models.URLField(verify_exists=False)
    title = models.CharField(max_length=255)
    blurb = models.TextField(blank=True)
    typ = models.CharField(choices=BUZZ_ITEM_TYPES, max_length=128, blank=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
   
    def __unicode__(self):
        return self.title
   

STATE_CHOICES= (
         ('0', 'Andaman and Nicobar'),
          ('1', 'Andhra Pradesh'),
          ('2', 'Arunachal Pradesh'),
          ('3', 'Asom (Assam)'),
          ('4', 'Bihar'),
          ('5', 'Chandigarh'),
          ('6', 'Chhattisgarh'),
          ('7', 'Dadra and Nagar Haveli'),
          ('8', 'Daman and Diu'),
          ('9', 'Delhi'),
          ('10', 'Goa'),
          ('11', 'Gujarat'),
          ('12', 'Haryana'),
          ('13', 'Himachal Pradesh'),
          ('14', 'Jammu And Kashmir'),
          ('15', 'Jharkhand'),
          ('16', 'Karnataka'),
          ('17', 'Kerala'),
          ('18', 'Lakshadweep'),
          ('19', 'Madhya Pradesh'),
          ('20', 'Maharashtra'),
          ('21', 'Manipur'),
          ('22', 'Meghalaya'),
          ('23', 'Mizoram'),
          ('24', 'Nagaland'),
          ('25', 'Odisha(Orrisa)'),
          ('26', 'Pondicherry'),
          ('27', 'Punjab'),
          ('28', 'Rajasthan'),
          ('29', 'Sikkim'),
          ('30', 'Tamilnadu'),
          ('31', 'Tripura'),
          ('32', 'Uttarakhand (Uttaranchal)'),
          ('33', 'Uttar Pradesh'),
          ('34', 'West Bengal')
)

class City(models.Model):
    name  = models.CharField(max_length=255)
    state = models.CharField(choices = STATE_CHOICES, max_length=255)


from django.contrib.localflavor.in_.forms import INZipCodeField
class Location(models.Model):
    lat= models.FloatField(blank=True, null=True)
    lon= models.FloatField(blank=True, null=True)
    city = models.ForeignKey(City)
    pincode= INZipCodeField() 
    address= models.TextField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

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


class PersonPerson(models.Model):
    person1 = models.ForeignKey(Person, related_name='PersonFrom', db_index=True)
    person2 = models.ForeignKey(Person, related_name='PersonTo', db_index=True, verbose_name='connection')
    relation = models.ForeignKey("Relation")
    disapproved = models.BooleanField(default=False)


class Relation(models.Model):
    name = models.CharField(max_length=255, db_index=True)
    reverse = models.CharField(max_length=255, db_index=True)

    def __unicode__(self):
        return self.name


class Training(models.Model):
    person = models.ForeignKey("Person")
    area = models.CharField(max_length=255) # Choices?
    with_whom = models.CharField(max_length=255) # Is this a foreign key to person, or group, or just text field like now?
    where = models.ForeignKey("TheatreGroup")
    from_when = models.DateField(blank=True, null=True)
    until_when = models.DateField(blank=True, null=True)


class Play(ItfModel):
    title = models.CharField(max_length=512)
    author = models.CharField(max_length=512, blank=True)
    year = models.IntegerField(null=True, blank=True, max_length=4)
    
    added_by = models.ForeignKey(User)
    
    def __unicode__(self):
        return self.title

  
class Production(ItfModel):
#    user = models.ForeignKey(User)
    fts_fields = ['name', 'group__name']
    form_names = ['ProductionForm', 'PopupProductionForm']
    main_form = 'ProductionForm'
    added_by = models.ForeignKey(User)
    script = models.ForeignKey(Script, blank=True, null=True)
    name = models.CharField(max_length=255, db_index=True)
    synopsis = models.TextField(blank=True)    
    language = models.ForeignKey("Language", blank=True, null=True)
    group = models.ForeignKey("TheatreGroup", blank=True, null=True)
    director = models.ForeignKey(Person, related_name='productions_directed', blank=True, null=True)
    playwright = models.ForeignKey(Person, related_name='productions_authored', blank=True, null=True)
    anecdotes = models.TextField(blank=True)    

    def __unicode__(self):
        return self.name

    def get_dict(self):
        return {
            'name': self.name,
            'anecdotes': self.anecdotes,
            'group': self.group,
            'director': self.director,
            'playwright': self.playwright
        }



SHOWS_NO_CHOICES = (
    ('5', '0-5 Shows'),
    ('10', '6-10 Shows'),
    ('50', '11-50 Shows'),
    ('100', '51-100 Shows'),
    ('1000', 'More Than 100 Shows'),
#add more.
)

class PersonProduction(models.Model):
    person = models.ForeignKey(Person, db_index=True)
    production = models.ForeignKey(Production, db_index=True)
    role = models.CharField(max_length=255)
    start_year = models.IntegerField(max_length=4)
    years = models.IntegerField(blank=True, null=True)
    no_of_shows = models.CharField(max_length=25, choices = SHOWS_NO_CHOICES)  
    original_cast = models.BooleanField(default=False)

class TheatreGroup(ItfModel):
    fts_fields = ['name', 'about']
    form_names = ['TheatreGroupForm', 'PopupGroupForm']
    main_form = 'TheatreGroupForm'
    added_by = models.ForeignKey(User)
    name = models.CharField(max_length=255, db_index=True) # name + location is unique
    email = models.EmailField(blank=True, null=True)
#    location = models.ForeignKey(Location, blank=True, null=True, related_name="theatregroup_location")
    tel = models.IntegerField(blank=True, null=True)
    # -- FIXME tel = models.CharField(blank=True, null=True)
    nature_of_work = models.ManyToManyField("GroupOccupation", blank=True, null=True, through="GroupGroupOccupation")
    languages = models.ManyToManyField("Language", blank=True, null=True)
    year_founded = models.IntegerField(blank=True, null=True)
    about = models.TextField(blank=True)
    awards = generic.GenericRelation("Award")
    buzzitems = generic.GenericRelation("BuzzItem")
    website = models.URLField(blank=True, verify_exists=False)
#    resources = models.ManyToManyField("Resource", blank=True, null=True)        
    locations = generic.GenericRelation("Location"), 
#    locations = models.ManyToManyField("Location", blank=True, null=True, related_name="theatregroup_locations")       
    
    about = models.TextField(blank=True, null=True)
    nature_of_work = models.CharField(max_length=255)
    founded = models.CharField(max_length=10)


    def __unicode__(self):
        return self.name

    def get_dict(self):
        return {
            'name': self.name,
            'about': self.about,
            'email': self.email,
            'tel':self.tel,
            'nature_of_work': [ obj for obj in self.nature_of_work_set.all()],
            'venues': [obj for obj in self.locations_set.alll()]
        }

    def get_title(self):
        return self.__unicode__()

class PersonGroup(models.Model):
    person = models.ForeignKey(Person, db_index=True)
    group = models.ForeignKey(TheatreGroup, db_index=True)
    is_admin = models.BooleanField(default=False)
    role = models.CharField(max_length=255, blank=True)







class Award(models.Model):
    title = models.CharField(max_length=255)
    year = models.IntegerField(blank=True)
    link = models.URLField(verify_exists=False, blank=True, null=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.title

class GroupOccupation(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class GroupGroupOccupation(models.Model):
    theatregroup = models.ForeignKey("TheatreGroup")
    groupoccupation = models.ForeignKey("GroupOccupation")
    is_main = models.BooleanField(default=False)
    


class Language(models.Model):
    code = models.CharField(max_length=3, db_index=True)
    name = models.CharField(max_length=255)

