from django.db import models
import datetime
import time
from ckeditor.fields import RichTextField
from app.models import ItfModel
from padmavideos.models import PadmaClip
from django.contrib.contenttypes import generic

class Comment(models.Model):
  name = models.CharField(max_length=255)
  email = models.EmailField(max_length=255)
  comment = models.TextField()
  is_displayed = models.BooleanField(default=True)
  meeting = models.ForeignKey('Meeting')
  parent = models.ForeignKey('Comment', default=0, related_name='child')
  posted_date = models.DateTimeField(default=datetime.datetime.now())
  
  def __unicode__(self):
    return "%s by %s on %s" % (self.comment, self.name, self.posted_date,)

  def epoch_date(self):
    return time.mktime(self.posted_date.timetuple())  


class CommentCaptcha(models.Model):
  question = models.CharField(max_length=500)
  answer = models.CharField(max_length=10)

  def __unicode__(self):
    return self.question

#Not using this class right now - but use this as a constant reminder ...
# class CommentVote(models.Model):
  

class Meeting(ItfModel):
  title = models.CharField(max_length=255)
  register_form_embed = models.TextField(blank=True, null=True)
  intro = models.TextField(blank=True, null=True)
  slug = models.SlugField()
  fts_fields = ['title', 'intro']  


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

  def __unicode__(self):
    return self.title

  def list_dict(self):
    return self.preview_dict()

  def main_image(self):
    if Image.objects.filter(meeting=self).count() > 0:
        img = Image.objects.filter(meeting=self)[0]
        return img.file
    else:
        return None

  def info_dict(self):
    meeting_data = {}
    meeting_data['meeting'] =  self
    meeting_id = self.id
#    meeting_data['sessions'] =  Session.objects.filter(day__meeting__id=meeting_id) # get meetings session objs
    meeting_data['days'] = [d.get_dict() for d in self.meetingday_set.all()]
    meeting_data['talks'] = Talk.objects.filter(session__day__meeting=self)
    meeting_data['images'] = Image.objects.filter(meeting=self)
    meeting_data['sessions'] = Session.objects.filter(day__meeting=self).order_by("day").order_by("session_no")
    meeting_data['documents'] = Document.objects.filter(meeting__id=meeting_id).exclude(talk__isnull=False)
    meeting_data['performances'] = [p.get_dict() for p in MeetingPerformance.objects.filter(meeting_day__meeting=self)]
    meeting_data['sponsors'] = MeetingSponsor.objects.filter(meeting=self)
    for s in meeting_data['sessions']:
      s.talks = Talk.objects.select_related('image', 'audio', 'document').filter(session__id=s.id)
      for t in s.talks:
        t.images = Image.objects.filter(talk__id=t.id)
        t.documents = Document.objects.filter(talk__id=t.id)
        t.audio = Audio.objects.filter(talk__id=t.id)
        t.video = Video.objects.filter(talk__id=t.id)

    meeting_data['imagegallery'] = Image.objects.filter(meeting=self)
#    meeting_data['participants'] = Participant.objects.filter(meeting__id=meeting_id).order_by('name')
    meeting_data['participants'] = self.participants.all()
    return meeting_data


class MeetingSponsor(models.Model):
  meeting = models.ForeignKey(Meeting)
  name = models.CharField(max_length=256)
  url = models.URLField(verify_exists=False, blank=True)
  logo = models.ImageField(upload_to='upload/meeting_logos', blank=True)

  def __unicode__(self):
    return self.name

class Participant(ItfModel):
  name = models.CharField(max_length=255)
  title = models.CharField(max_length=255, blank=True, null=True)
  short_bio = models.TextField(max_length=255, blank=True, null=True)
  meeting = models.ForeignKey('Meeting')
  meetings = models.ManyToManyField('Meeting', related_name='participants')
  videos = generic.GenericRelation(PadmaClip)

  fts_fields = ['name', 'title', 'short_bio']
  def __unicode__(self):
    return self.name

  def get_title(self):
    return self.name

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

  def info_dict(self):
    return {
      'id': self.id,
      'name': self.name,
      'title': self.title,
      'short_bio': self.short_bio,
      'meetings': self.meetings.all()
    }

  class Meta:
    ordering = ['name']

class Talk(models.Model):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  presenter = models.CharField(max_length=255, blank=True)
  session = models.ForeignKey('Session')             # name of meeting - name of session
  videos = generic.GenericRelation(PadmaClip)

  def __unicode__(self):
    return "%s - %s" % (self.session.day.meeting.title, self.title)           # name of meeting - name of session

  def get_dict(self):
    return {
      'title': self.title,
      'intro': self.intro,
      'presenter': self.presenter,
      'audios': self.audio_set.all(),
      'videos': self.video_set.all(),
      'documents': self.document_set.all()
    }

class Session(models.Model):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  day = models.ForeignKey('MeetingDay')
  session_no = models.IntegerField(blank=True, null=True)
  videos = generic.GenericRelation(PadmaClip)

  def __unicode__(self):
    return "%s - %s" % (self.day.meeting.title, self.title)                  # name of meeting - name of session

  def get_dict(self):
    return {
      'title': self.title,
      'intro': self.intro,
      'session_no': self.session_no,
      'talks': [t.get_dict() for t in self.talk_set.all()],
#      'videos': self.videos.all()
    }


class MeetingPerformance(models.Model):
  title = models.CharField(max_length=512)
  performed_by = models.CharField(max_length=512, blank=True, verbose_name="Group")
  director = models.CharField(max_length=512, blank=True)
  language = models.CharField(max_length=256, blank=True)
  synopsis = models.TextField(blank=True)
  time = models.TimeField(null=True, blank=True)
  meeting_day = models.ForeignKey("MeetingDay")
  

  class Meta:
    ordering = ['meeting_day', 'time']

  def get_dict(self):
    return {
      'title': self.title,
      'performed_by': self.performed_by,
      'director': self.director,
      'language': self.language,
      'synopsis': self.synopsis,
      'date': self.meeting_day.meeting_date,
      'time': self.time,
      'images': [i for i in MeetingPerformanceImage.objects.filter(performance=self)]   
    }

  def __unicode__(self):
    return self.title


class MeetingPerformanceImage(models.Model):
  performance = models.ForeignKey(MeetingPerformance)
  image = models.ImageField(upload_to='upload/images/')
  caption = models.CharField(max_length=512, blank=True)

  def __unicode__(self):
    return self.caption


class MeetingDay(models.Model):
  meeting = models.ForeignKey('Meeting')
  meeting_date = models.DateField()

  def __unicode__(self):
    return "%s - %s" % (self.meeting, self.meeting_date)

  def get_dict(self):
    return {
        'date': self.meeting_date,
        'sessions': [s.get_dict() for s in self.session_set.all()]
    }

class Audio(models.Model):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  file = models.FileField(upload_to='upload/audio')
  meeting = models.ForeignKey('Meeting', blank=True, null=True)
  talk = models.ForeignKey('Talk', blank=True, null=True)

  class Meta:
    verbose_name_plural = "Audio"

  def __unicode__(self):
    return self.title

class Video(models.Model):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  file = models.FileField(upload_to='upload/video')
  meeting = models.ForeignKey('Meeting', blank=True, null=True)
  talk = models.ForeignKey('Talk', blank=True, null=True)

  def __unicode__(self):
    return self.title
'''
class PadmaVideo(models.Model):
  padma_id = models.CharField(max_length=50)
  talk = models.ForeignKey('Talk')

  def __unicode__(self):
    return self.padma_id
'''

class Image(models.Model):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  file = models.FileField(upload_to='upload/images')
  meeting = models.ForeignKey('Meeting', blank=True, null=True)
  talk = models.ForeignKey('Talk', blank=True, null=True)

  def __unicode__(self):
    return self.title



class DocumentSubject(ItfModel):
  title = models.CharField(max_length=255)
  main_image = models.ImageField(upload_to='upload/images/festival/main/', blank=True, null=True)

  fts_fields = ['title', 'document__title', 'document__intro']
  def __unicode__(self):
    return self.title

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

  def info_dict(self):
    return {
      'id': self.id,
      'title': self.title,
      'documents': [d.info_dict() for d in Document.objects.filter(subject=self)]
    }

class Document(ItfModel):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  file = models.FileField(upload_to='upload/docs', blank=True, null=True)
  meeting = models.ForeignKey('Meeting', blank=True, null=True)
  talk = models.ForeignKey('Talk', blank=True, null=True)
  is_resource = models.BooleanField()
  subject = models.ForeignKey('DocumentSubject', blank=True, null=True)
  link = models.URLField(verify_exists=False, blank=True)

  fts_fields = ['title', 'intro']
  fk_filters = []
  sort_fields = ['title']


  def preview_dict(self):
    return {
      'id': self.id,
      'title': self.title,
      'intro': self.intro,
      'file': self.file.url if self.file else ''
    }

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

  def info_dict(self):
    return self.preview_dict()

  def __unicode__(self):
    return self.title

  @classmethod
  def get_qset(kls):
    return kls.objects.filter(is_resource=True)


class Project(ItfModel):
  title = models.CharField(max_length=255)
  intro = models.TextField(blank=True, null=True)
  start_date = models.DateField(blank=True, null=True)
  end_date = models.DateField(blank=True, null=True)
  slug = models.SlugField()

  fts_fields = ['title', 'intro']
  fk_filters = []
  sort_fields = ['title', 'start_date']  

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

  def info_dict(self):
    return self.preview_dict()

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

  def __unicode__(self):
    return self.title

class Signup(models.Model):
  email = models.EmailField()

  def __unicode__(self):
    return self.email
