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 itfprofiles.models import City, Location, Production, TheatreGroup, Person, BuzzItem
from mediagallery.models import GalleryAlbum


EVENT_TYPE_CHOICES = (
    ('workshop', 'Workshop'),
    ('talk', 'Talk'),
    ('performance', 'Performance'),
    ('festival', 'Festival'),
    ('other', 'Other'),
)

class Event(ItfModel):
    #ItfModel stuff:
    form_names = ['EventForm']
    main_form = 'EventForm'
    fts_fields = ['title', 'oneliner', 'description']
    added_by = models.ForeignKey(User, editable=False, null=True, blank=True)
    title = models.CharField(max_length=1024)
    event_type = models.CharField(choices=EVENT_TYPE_CHOICES, max_length=64, blank=True)
    oneliner = models.CharField(max_length=1024,help_text="Event slogan/one liner", blank=True)
    description = models.TextField(blank=True, null=True)
    parent_event = models.ForeignKey("Event", related_name='child_events', help_text='If this event is part of another event', blank=True, null=True)
    city = models.ForeignKey(City, blank=True, null=True)
    address = models.TextField(blank=True)
#    location = models.ForeignKey(Location)
#    locations = generic.GenericRelation(Location) 
    start_date = models.DateField()
    end_date = models.DateField(null=True, blank=True, help_text='If event is on a single day, leave blank')
    start_time = models.TimeField(null=True, blank=True)    
    end_time = models.TimeField(null=True, blank=True)
    booking_link = models.URLField(blank=True, null=True, help_text="Ticket booking link")
    tel_no = models.CharField(max_length=100, blank=True)
    production = models.ForeignKey(Production, blank=True, null=True, help_text="If this is a showing of a production...") 
    buzzitems = generic.GenericRelation(BuzzItem)   
    galleries = generic.GenericRelation(GalleryAlbum)
    people = models.ManyToManyField(Person, blank=True, null=True, through="PersonEvent")  
    image = models.ImageField(upload_to='images/', blank=True, null=True)
    groups = models.ManyToManyField(TheatreGroup, blank=True, null=True, through="GroupEvent")
    
#Entities and Connections - 
#    connections = generic.GenericRelation("Connection")


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

    def get_dict(self):
#        links = self.connections.all().order_by('link_type')
#        link_keys =   self.connections.all().values_list['link_type'].distinct()

#        conn = dict()
#        for key in link_keys:
#            conn[key]= [obj for obj in links if obj.type==key]
       #add conn keys to main dict 
        rdict = {
            'title': self.title,
            'oneliner': self.oneliner,
            'description': self.description,
            'event_type': self.event_type,
            'oneliner':self.oneliner,
            'is_child': True if self.parent_event != None else False,
            'city': self.city,
            'address':self.address,
            'start_date':self.start_date,
            'end_date': self.end_date,
            'start_time': self.start_time,
            'end_time':self.end_time,
            'booking_link': self.booking_link,
            'tel_no':self.tel_no,
            'image':self.image,
            'production':self.production,   
            'buzzitems': [ obj for obj in self.buzzitems.all()],
            'groups':  [obj for obj in self.groupevent_set.all()], 
            'galleries': [obj for obj in self.galleries.all()], 
            'child_events': self.child_events.all(),
            'parent':self.parent_event,
            'has_people_tab': False
       }
        if self.groups.all():
            groups= {
            'venue': [ obj.group for obj in self.groupevent_set.filter(typ='venue')],           
            'performing':  [ obj.group for obj in self.groupevent_set.filter(typ='performing')]
            }
            rdict['groups']= groups
            rdict['has_people_tab'] = True
 
        if self.people.all():
            people= {
            'attendees': [ obj.person for obj in self.personevent_set.filter(typ='attendee')],
            'organisers':  [ obj.person for obj in self.personevent_set.filter(typ='organiser')],
            'performers':  [ obj.person for obj in self.personevent_set.filter(typ='performer')]
            }
            rdict['people']= people
            rdict['has_people_tab'] = True       
           
        return rdict
        

PERSON_EVENT_CHOICES = (
    ('attendee', 'Attendee'),
    ('organiser', 'Organiser'),
    ('performer', 'Performer'),
)

class PersonEvent(models.Model):
    person = models.ForeignKey(Person)
    event = models.ForeignKey(Event)
    typ = models.CharField(choices=PERSON_EVENT_CHOICES, max_length=128)


GROUP_EVENT_CHOICES = (
    ('venue', 'Venue'),
    ('performing', 'Performing'),
)

class GroupEvent(models.Model):
    group = models.ForeignKey(TheatreGroup)
    event = models.ForeignKey(Event)
    typ = models.CharField(choices=GROUP_EVENT_CHOICES, max_length=128)


#class Connection(models.Model):
#    link_type = models.CharField(max_length=255)
#    extra_text = models.CharField(max_length=1024)   
#    content_type = models.ForeignKey(ContentType)
#    object_id = models.PositiveIntegerField()
#    content_object = generic.GenericForeignKey('content_type', 'object_id')

#    def __unicode__(self):
#        return self.link_type

