from uuid import uuid4

from django.shortcuts import get_object_or_404, redirect
from django.views.generic.base import TemplateView, View
from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.contrib.auth.decorators import permission_required

from core.storage import Storage
from core.models import Badge

from app.forms import BadgeForm

from django_yauth.decorators import yalogin_required


class BadgeView(TemplateView):

    template_name = 'badge_list.html'

    def get_context_data(self, **kwargs):
        context = super(BadgeView, self).get_context_data(**kwargs)
        context['badges'] = Badge.objects.all()
        return context

    def get(self, request, badge_id=None):
        """
            List all badges.
        """
        context = self.get_context_data()
        if badge_id is not None:
            context['badge_id'] = int(badge_id)
        badge = None
        if badge_id is not None:
            badge = get_object_or_404(Badge, pk=badge_id)
            context['badge'] = badge
        context['form'] = BadgeForm(instance=badge)
        return self.render_to_response(context)

    def post(self, request, badge_id=None):
        """
            Creating or updating badge.
        """
        badge = None
        if badge_id is not None:
            badge = get_object_or_404(Badge, pk=badge_id)
        form = BadgeForm(request.POST, request.FILES, instance=badge)
        if form.is_valid():
            badge = form.save(commit=False)
            data = form.cleaned_data
            filename = data.get('image', None)
            if filename is not None:
                filename = data['image'].temporary_file_path()
                s = Storage()
                key = uuid4().hex
                image_url = s.put(key, filename)
                badge.image_url = image_url.replace('http://', 'https://')
            badge.save()
            messages.success(request, _('Badge was successfully added'))
            return redirect('badge', badge.id)
        else:
            messages.error(request, _('Unable to add badge'))

        context = self.get_context_data()
        context['form'] = form
        if badge_id is not None:
            context['badge'] = badge
        return self.render_to_response(context)

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.add_badge', raise_exception=True))
    @method_decorator(permission_required('core.change_badge', raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(BadgeView, self).dispatch(request, *args, **kwargs)


class DeleteBadge(View):

    def post(self, request, badge_id):
        Badge.objects.filter(pk=badge_id).delete()
        return redirect('badge')

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.delete_badge', raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(DeleteBadge, self).dispatch(request, *args, **kwargs)
