# -*- 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 extra_views import ModelFormSetView, InlineFormSetView
from django.http import HttpResponse, 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
from icalendar import Calendar, Event
import pyexiv2

from utils.mixins import PermissionRequiredMixin
from . import models, forms


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
    queryset = model.objects.all()
    paginate_by = 15


    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


class EventDetailMixin(object):

    def get_context_data(self, **kwargs):
        context = super(EventDetailMixin, self).get_context_data(**kwargs)
        if hasattr(self, 'event'):
            context['event'] = self.event
        else:
            context['event'] = self.object.event
        return context


class EventForm(PermissionRequiredMixin, generic.UpdateView):
    form_class = forms.EventForm
    template_name = 'events/event_form.html'
    permission_required = 'events.add_event'

    def get_context_data(self, **kwargs):
        context = super(EventForm, self).get_context_data(**kwargs)
        if self.kwargs.get('pk'):
            context['title'] = _("Edit Event")
        else:
            context['title'] = _("Add Event")
        return context

    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()


class EventSeriesForm(EventDetailMixin, PermissionRequiredMixin, InlineFormSetView):
    model = models.Event
    inline_model = models.Event
    fk_name = 'event_series'
    fields = ('start', 'end')
    form_class = forms.EventForm
    extra = 3
    permission_required = 'events.add_event'
    template_name = 'events/eventseries_form.html'

    def get_object(self, queryset=None):
        self.event = models.Event.objects.get(pk=self.kwargs['pk'])
        if self.event.event_series:
            self.event = self.event.event_series
        return self.event


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


class EventListIcal(generic.View):
    """
    Generates an returns an iCal File with all upcoming events.
    """

    def add_event(self, event):
        ics_event = Event()
        dtstart = timezone.localtime(event.start)
        dtend = timezone.localtime(event.end)

        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('URL', '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:
            ics_event.add('DTEND', dtend)
        self.calendar.add_component(ics_event)

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


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

    def get_context_data(self, **kwargs):
        context = super(EventPhoto, self).get_context_data()
        event = models.Event.objects.get(id=self.kwargs['event'])
        context['event'] = event
        return context

    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'])
            # 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 = models.Event.objects.get(id=self.kwargs['event'])
            return models.Photo.objects.filter(event=self.event)
        except models.Event.DoesNotExist:
            raise Http404(_('Event does not exist'))


class EventPhotoUpload(generic.FormView):
    form_class = forms.PhotoUploadForm
    template_name = 'events/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'] = 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):
        """

        """
        self.event = models.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 = models.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


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