from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.contrib.contenttypes import generic
from app.models import ItfModel
from itfprofiles.models import TheatreGroup
from mediagallery.models import GalleryAlbum

GENRES = (
    ('Fiction', 'Fiction'),
    ('Comedy', 'Comedy'),
)

LICENSE_TYPE_CHOICES = (
    ('adapt', 'Adaptation License'),
    ('perform', 'Performance License'),
)

LANGUAGE_CHOICES = (
    ('en', 'English'),
    ('hi', 'Hindi'),
    ('ma', 'Marathi'),
    ('be', 'Bengali'),
)

class Script(ItfModel):
    added_by = models.ForeignKey(User)
    form_names = ['ScriptForm', 'PopupScriptForm']
    main_form = 'ScriptForm'
    title = models.CharField(max_length=255, help_text="Title of the play")
    synopsis = models.TextField(blank=True)
    no_characters = models.IntegerField(blank=True, null=True, verbose_name="No of characters", help_text="Approximate number of characters")
    no_of_women = models.IntegerField(blank=True, null=True, help_text="How many characters are women?")
    tags = TagField(blank=True, help_text="Enter as many tags as you like, separated by commas")
    production_notes = models.TextField(blank=True, help_text="Additional production notes")
    language = models.CharField(max_length=32, choices=LANGUAGE_CHOICES)
    approx_duration = models.IntegerField(blank=True, null=True, verbose_name="Approximate duration", help_text="Approximate time, in minutes")
    author = models.CharField(max_length=255, help_text="Name of the author of the play")
    contact = models.EmailField()
    script = models.FileField(null=True, upload_to='upload/scripts/')  
    is_partial = models.BooleanField(default=False, verbose_name="Is this a partial script upload?", help_text="Check this if you are uploading only a partial script")
    license_adapt = models.ForeignKey("License", related_name="adaptation_license", verbose_name="Adaptation License", help_text="License for adaptation rights")
    license_perform = models.ForeignKey("License", related_name="performance_license", verbose_name="Performance License", help_text="License for performance rights")
    fts_fields = ['title', 'synopsis', 'author']
    fk_fields = ['license_adapt', 'license_perform']  
    theatre_group = models.ForeignKey(TheatreGroup, help_text="Theatre Group, if any")
    related_scripts = models.ManyToManyField("Script", through="ScriptScript", related_name='related_script')
    galleries = generic.GenericRelation(GalleryAlbum)
#  add_form = 'ScriptForm'

  #Meta
    added = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title  

    def user_has_perms(self, user):
        if self.added_by_id == user.id:
            return True
        return self.theatre_group.user_has_perms(user)

    def list_dict(self):
       return {
           'id': self.id,
           'title': self.title,
       }

    def no_of_men(self):
        if not self.no_characters:
            return False
        if self.no_of_women:
            return self.no_characters - self.no_of_women
        else:
            return self.no_characters

    def get_dict(self):
        return {
            'title': self.title,
            'synopsis': self.synopsis,
            'no_characters': self.no_characters,
            'no_of_women': self.no_of_women,
            'no_of_men': self.no_of_men(),
            'production_notes': self.production_notes,
            'language': self.language,
            'approx_duration': self.approx_duration,
            'is_partial': self.is_partial,
            'author': self.author,
            'contact': self.contact,
            'script_file': self.script.url,
            'license_adapt': self.license_adapt,
            'license_perform': self.license_perform,
            'productions': self.production_set.all(),
            'related_scripts': self.related_scripts,
            'related_people': self.related_people()
        }
    
    def related_people(self):
        people =  []
        for p in self.production_set.all():
            if p.get_people():
                people.extend(p.get_people())

        script_auths = [ {"person":s.author, "role":"author", "assoc_type":"related_script", "assoc_name":s.title } for s in self.related_scripts.all() ]
        if script_auths:
            people.extend(script_auths)
        return people


SCRIPT_RELATIONS = (
    ('adaptation', 'Adaptation Of'),
    ('translation', 'Translation Of')
)

class ScriptScript(models.Model):
    script1 = models.ForeignKey(Script, related_name='related_from')
    script2 = models.ForeignKey(Script, related_name='related_to')
    relation_type = models.CharField(choices=SCRIPT_RELATIONS, max_length=64)


class License(ItfModel):
  letter = models.CharField(max_length=2)
  name = models.CharField(max_length=255)
  short_description = models.TextField()
  readable_file = models.FileField(upload_to='upload/licenses/short/')
  legal_file = models.FileField(upload_to='upload/licenses/legal/') 
  typ = models.CharField(choices=LICENSE_TYPE_CHOICES, max_length=32)

  title_field = 'name'

  def __unicode__(self):
    return self.typ + ": " + self.letter + ": " + self.name

  def list_dict(self):
    return {
      'id': self.id,
      'title': self.name
    }

  def info_dict(self, request=None):
    return {
      'id': self.id,
      'letter': self.letter,
      'short_description': self.short_description,
      'readable_file': self.readable_file.url,
      'legal_file': self.legal_file.url,
      'typ': self.typ,
      'reviews': Review.objects.filter(script=self)
    }

class Review(models.Model):
  script = models.ForeignKey(Script)
  reviewer = models.CharField(max_length=255)
  reviewer_email = models.EmailField()
  text = models.TextField()



#this is to record who downloaded what play, etc.
class Downloader(models.Model):
  script = models.ForeignKey(Script)
  email = models.EmailField()

##Make sure to add Comments to scripts


