# Create your views here.
from . import models, forms
from datetime import datetime
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.views import generic
from utils.icalendar import Calendar, Event
from dateutil.tz import gettz
import pyexiv2

class DeleteEventPhoto(generic.DeleteView):
    model = models.Photo
    """
    def get_object(self, queryset=None):
        return models.Photo.objects.get(pk=self.kwargs['pk'])
    """
    def get_success_url(self):
        return reverse('event-photo-list', args=[self.object.event.id])

    @method_decorator(permission_required('events.delete_photo'))
    def dispatch(self, *args, **kwargs):
        return super(DeleteEventPhoto, self).dispatch(*args, **kwargs)

class EventArchiveIndex(generic.ArchiveIndexView):
    allow_empty = True
    context_object_name = 'event_list'
    date_field = 'start'
    model = models.Event
    paginate_by = 5
    
    def get_context_data(self, **kwargs):
        context = generic.ArchiveIndexView.get_context_data(self, **kwargs)
        context['is_archive'] = True
        return context
    
class EventArchiveMonth(generic.MonthArchiveView):
    date_field = 'start'
    make_object_list = True    
    model = models.Event
    month_format = '%m'    
    paginate_by = 15
    template_name = 'events/event_archive.html'

    def get_context_data(self, **kwargs):
        context = generic.MonthArchiveView.get_context_data(self, **kwargs)
        context['is_archive'] = True
        return context

class EventArchiveYear(generic.YearArchiveView):
    date_field = 'start'
    make_object_list = True    
    model = models.Event
    paginate_by = 15
    template_name = 'events/event_archive.html'
    year_format = '%Y'    

    def get_context_data(self, **kwargs):
        context = generic.YearArchiveView.get_context_data(self, **kwargs)
        context['is_archive'] = True
        return context

class EventDetail(generic.DetailView):
    model = models.Event
    
    def get_context_data(self, **kwargs):
        context =  generic.DetailView.get_context_data(self, **kwargs)
        context['form'] = forms.PhotoUploadForm(initial={'event':self.object, 'photographer': self.request.user})
        return context
    
class EventForm(generic.UpdateView):
    template_name = 'events/event_form.html'
    form_class = forms.EventForm

    def get_object(self, queryset=None):
        '''
        If an id has been submitted, try return the existing Event for an update,
        else creates a new one.
        @param queryset:
        '''
        if self.kwargs.get('pk'):
            return models.Event.objects.get(pk=self.kwargs['pk'])
        else: 
            return models.Event()

    @method_decorator(permission_required('events.update_event'))
    def dispatch(self, *args, **kwargs):
        return super(EventForm, self).dispatch(*args, **kwargs)


class EventGallery(generic.ListView):
    template_name = 'events/event_gallery.html'
    queryset = models.Event.objects.filter(start__lt=datetime.now(), photo_count__gt=0)
    
class EventListIcal(generic.View):
    '''
    Generates an returns an iCal File with all upcoming events.
    '''

    def add_event(self, event):
        ics_event = Event()
        dtstart = event.start.replace(tzinfo=self.tzinfo)        

        ics_event.add('dtstart', dtstart)
        ics_event.add('summary', event.name)
        ics_event.add('description', event.description)
        ics_event.add('location', event.location.address)
        ics_event.add('attach', 'http://www.kasu.at' + event.get_absolute_url())
        ics_event['uid'] = 'event-%d@www.kasu.at' % event.pk
        ics_event.add('priority', 5)
        if event.end:
            dtend = event.end.replace(tzinfo=self.tzinfo)        
            ics_event.add('dtend', dtend)

        self.calendar.add_component(ics_event)

    def get(self, request, *args, **kwargs):
        response = HttpResponse() #mimetype="text/calendar; charset=UTF-8")
        self.calendar = Calendar()
        self.calendar.add('prodid', 'http://www.kasu.at/')
        self.calendar.add('version', '2.0')
        self.tzinfo = gettz('CET')
        for event in models.Event.objects.upcoming(limit=None):
            self.add_event(event)
        response.write(self.calendar.as_string())
        return response


class EventPhoto(generic.UpdateView):
    form_class = forms.EditPhotoForm
    model = models.Photo
    template_name = 'events/event_photo.html'
  
    def post(self, request, *args, **kwargs):
        if request.POST.get('rotate') and request.user.has_perm('events.change_photo'):
            photo = models.Photo.objects.get(pk=kwargs['pk'])
            photo.rotate(request.POST['rotate'])
            photo.save()
            #return redirect(photo.get_absolute_url())
            return self.get(request)
        else:
            return generic.UpdateView.post(self, request, *args, **kwargs)

class EventPhotoList(generic.ListView):
    context_object_name = 'photo_list'
    paginate_by = 36
    template_name = 'events/event_photolist.html'
    
    def get_context_data(self, **kwargs):
        context =  generic.ListView.get_context_data(self, **kwargs)
        context['event'] = self.event
        context['form'] = forms.PhotoUploadForm(initial={'event':self.event, 'photographer': self.request.user})
        print self.event.get_absolute_url()
        return context

    def get_queryset(self):
        self.event = models.Event.objects.get(id=self.kwargs['event'])
        return models.Photo.objects.filter(event=self.event)
    
class EventPhotoUpload(generic.FormView):
    form_class = forms.PhotoUploadForm
    template_name = 'events/upload_photo.html'
    
    @method_decorator(permission_required('event.add_photo'))
    def dispatch(self, *args, **kwargs):
        return super(EventPhotoUpload, self).dispatch(*args, **kwargs)

    def get_context_data(self, **kwargs):
        context = generic.FormView.get_context_data(self, **kwargs)
        context['event_list'] = models.Event.objects.archive()[:12]
        return context

    def get_initial(self):
        '''
        Set the current logged in user a default value for the photographer.
        '''
        return {
            'photographer': self.request.user,
        }

    def post(self, *args, **kwargs):
        '''
        
        '''
        event = models.Event.objects.get(id=self.request.REQUEST.get('event'))
        photographer = self.request.POST.get('photographer')
        if photographer:
            photographer = User.objects.get(id=photographer)
        else:
            photographer = self.request.user

        for upload in self.request.FILES.getlist('upload'):
            name = upload.name
            created_date, description = self.read_exif(upload)
            photo = models.Photo(
                event=event, 
                photographer=photographer, 
                image=upload,
                name=name,
                created_date=created_date,
                description=description
            )                                   
            photo.save()
        return redirect('event-photo-list', event=event.id)
    
    def read_exif(self, photo):
        exif_data = pyexiv2.ImageMetadata.from_buffer(photo.read())
        exif_data.read()
        
        try:
            created_date = exif_data['Exif.Image.DateTime'].value
        except:
            created_date = datetime.now()
        try:
            description = exif_data['Exif.Image.ImageDescription'].value
        except:
            description = ''
        return (created_date, description)

class UpcomingEvents(generic.ListView):
    queryset = models.Event.objects.upcoming(limit=None)
    paginate_by = 12
