# -*- encoding: utf-8 -*-
# Create your views here.
from datetime import timedelta

from django.contrib.auth.decorators import permission_required
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.views import generic
import pyexiv2

from events.models import Event
from .models import Photo
from . import forms


class DeleteEventPhoto(generic.DeleteView):
    model = Photo

    def get_success_url(self):
        return reverse('event-photo-list', args=[self.object.event.id])

    def get_context_data(self, **kwargs):
        context = super(DeleteEventPhoto, self).get_context_data()
        context['event'] = self.object.event
        return context

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


class EventGallery(generic.ListView):
    template_name = 'gallery/photo_gallery.html'
    queryset = Event.objects.filter(start__lt=timezone.now(), photo_count__gt=0)
    paginate_by = 12


class EventPhoto(generic.UpdateView):
    form_class = forms.EditPhotoForm
    model = Photo
    template_name = 'gallery/photo_detail.html'

    def get_context_data(self, **kwargs):
        context = super(EventPhoto, self).get_context_data()
        context['event'] = self.object.event
        return context

    def post(self, request, *args, **kwargs):
        if request.POST.get('rotate') and request.user.has_perm(
                'events.change_photo'):
            photo = Photo.objects.get(pk=kwargs['pk'])
            photo.rotate(request.POST['rotate'])
            # 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

    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})
        return context

    def get_queryset(self):
        try:
            self.event = Event.objects.get(id=self.kwargs['event'])
            return Photo.objects.filter(event=self.event)
        except Event.DoesNotExist:
            raise Http404(_('Event does not exist'))


class EventPhotoUpload(generic.FormView):
    form_class = forms.PhotoUploadForm
    template_name = 'gallery/photo_upload.html'

    @method_decorator(permission_required('events.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'] = 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):
        """

        """
        self.event = Event.objects.get(
            id=self.request.REQUEST.get('event'))
        photographer = self.request.POST.get('photographer',
                                             self.request.user.id)
        photographer = get_user_model().objects.get(id=photographer)
        self.counter = 1
        for upload in self.request.FILES.getlist('upload'):
            name = upload.name
            created_date, description = self.read_exif(upload)
            photo = Photo(
                event=self.event,
                photographer=photographer,
                image=upload,
                name=name,
                created_date=created_date,
                description=description
            )
            photo.save()
            self.counter += 1
        return redirect('event-photo-list', event=self.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 = self.event.start + timedelta(minutes=self.counter)
        try:
            description = exif_data['Exif.Image.ImageDescription'].value
        except:
            description = ''
        return created_date, description

