# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import http
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.db import models as django_models
from django.views import generic as views
from django.utils.translation import gettext_lazy as _

from app import forms
from core import models


__all__ = ['ListProduct', 'UpdateProduct', 'CreateProduct', 'DeleteProduct']


class ListProduct(views.ListView):
    model = models.Product
    template_name = 'product_list.html'


class BaseProductMixin(object):
    model = models.Product
    success_url = reverse_lazy('product:list')


class ProductFormMixin(BaseProductMixin):

    def form_valid(self, form):
        messages.success(self.request, self.success_message)
        return super(BaseProductMixin, self).form_valid(form)


class CreateProduct(ProductFormMixin, views.CreateView):
    form_class = forms.ProductForm
    template_name = 'product.html'
    success_message = _('Product successfully created')


class UpdateProduct(ProductFormMixin, views.UpdateView):
    form_class = forms.ProductForm
    template_name = 'product.html'
    success_message = _('Product successfully updated')


class DeleteProduct(BaseProductMixin, views.DeleteView):
    success_message = _('Product successfully deleted')
    error_message = _("Can't delete product: it has linked rewards")

    def delete(self, request, *args, **kwargs):
        try:
            redirect = super(DeleteProduct, self).delete(request, *args, **kwargs)
        except django_models.ProtectedError:
            messages.error(request, self.error_message)
            return http.HttpResponseRedirect(self.success_url)
        else:
            messages.success(request, self.success_message)
            return redirect
