from datetime import datetime
from django import forms
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, Http404
from django_mako_plus.controller import view_function
from .. import dmp_render, dmp_render_to_response

from account.models import User
from catalog.models import Product, RentalProduct, IndividualProduct, BulkProduct, PRODUCT_TYPE_CHOICES, RENTAL_STATUS_CHOICES

##
# Show
#
@view_function
def process_request(request):
    products = Product.objects.all().order_by('name')

    template_vars = {
        'products' : products,
    }

    return dmp_render_to_response(request, 'products.show.html', template_vars)

##
# Update Quantity
#
@view_function
@permission_required('catalog.change_product', login_url='/homepage/index/')
def get_quantity(request):
    # Return 404 if it doesn't exist or if the product isn't bulk
    try:
        product = BulkProduct.objects.get(id=request.urlparams[0])
    except BulkProduct.DoesNotExist:
        raise Http404("Product Does Not Exist")

    return JsonResponse({
        'quantity' : product.quantity
    })

##
# Create
#
@view_function
@permission_required('catalog.add_product', login_url='/homepage/index/')
def new(request):
    form = CreateProductForm()

    if request.method == 'POST':
        form = CreateProductForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            if data.get('product_type') == 'RentalProduct':
                p = RentalProduct()
                p.status = data.get('rental_status')
            elif data.get('product_type') == 'IndividualProduct':
                p = IndividualProduct()
                p.creator = data.get('creator')
            elif data.get('product_type') == 'BulkProduct':
                p = BulkProduct()
                p.quantity = data.get('quantity')

            p.name = data.get('name')
            p.image = data.get('image')
            p.description = data.get('description')

            p.save()

            return HttpResponseRedirect('/catalog/products')

    template_vars = {
        'form': form,
    }
    return dmp_render_to_response(request, 'products.new.html', template_vars)

class CreateProductForm(forms.Form):
    name = forms.CharField(label="Product Name", required=True, widget=forms.TextInput(attrs={'class' : 'form-control'}))
    image = forms.CharField(label="Product Image", required=True, widget=forms.TextInput(attrs={'class' : 'form-control'}))
    description = forms.CharField(label="Product Description", required=True, widget=forms.Textarea(attrs={'class' : 'form-control', 'rows' : 4}))
    product_type = forms.ChoiceField(label='Product Type', required=True, choices=PRODUCT_TYPE_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
    rental_status = forms.ChoiceField(label='Rental Status', required=False, choices=RENTAL_STATUS_CHOICES, widget=forms.Select(attrs={'class' : 'form-control rental product-specific-field'}))
    creator = forms.ModelChoiceField(label='Creator', required=False, empty_label=None, queryset=User.objects.all(), widget=forms.Select(attrs={'class' : 'form-control individual product-specific-field'}))
    quantity = forms.IntegerField(label='Quantity', required=False, widget=forms.TextInput(attrs={'class' : 'form-control product-specific-field bulk'}))

    def clean_product_type(self):
        product_type = self.cleaned_data.get('product_type')
        valid_product_type = False

        for t in PRODUCT_TYPE_CHOICES:
            if t[0] == product_type:
                valid_product_type = True

        if not valid_product_type:
            raise forms.ValidationError('Invalid Product Type.')

        return product_type

##
# Edit
#
@view_function
@permission_required('catalog.change_product', login_url='/homepage/index/')
def edit(request):
    try:
        product = Product.objects.get(id=request.urlparams[0])
    except Product.DoesNotExist:
        return HttpResponseRedirect('/catalog/products/')

    class_name = product.__class__.__name__

    if class_name == "BulkProduct":
        form = BulkProductForm(request.POST or None, instance=product)
    elif class_name == "RentalProduct":
        form = RentalProductForm(request.POST or None, instance=product)
    elif class_name == "IndividualProduct":
        form = IndividualProductForm(request.POST or None, instance=product)
    else:
        return HttpResponseRedirect('/catalog/products/')

    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/catalog/products.edit/%i' % product.id)

    template_vars = {
        'form' : form,
        'product' : product,
    }

    return dmp_render_to_response(request, 'products.edit.html', template_vars)

class EditProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'

    name = forms.CharField(label="Product Name", required=True, widget=forms.TextInput(attrs={'class': 'form-control'}))
    image = forms.CharField(label="Product Image", required=True, widget=forms.TextInput(attrs={'class' : 'form-control'}))
    description = forms.CharField(label="Product Description", required=True, widget=forms.Textarea(attrs={'class' : 'form-control', 'rows' : 4}))

class BulkProductForm(EditProductForm):
    class Meta:
        model = BulkProduct
        fields = '__all__'

    quantity = forms.IntegerField(label='Quantity', required=False, widget=forms.TextInput(attrs={'class' : 'form-control product-specific-field bulk'}))

class RentalProductForm(EditProductForm):
    class Meta:
        model = RentalProduct
        fields = '__all__'

    status = forms.ChoiceField(label='Rental Status', required=False, choices=RENTAL_STATUS_CHOICES, widget=forms.Select(attrs={'class' : 'form-control rental product-specific-field'}))

class IndividualProductForm(EditProductForm):
    class Meta:
        model = IndividualProduct
        fields = '__all__'

    creator = forms.ModelChoiceField(label='Creator', required=False, empty_label=None, queryset=User.objects.all(), widget=forms.Select(attrs={'class' : 'form-control individual product-specific-field'}))

##
# Delete
#
@view_function
@permission_required('catalog.delete_product', login_url='/homepage/index/')
def delete(request):
    try:
        product = Product.objects.get(id=request.urlparams[0])
    except Product.DoesNotExist:
        return HttpResponseRedirect('/catalog/products/')

    product.delete()

    return HttpResponseRedirect('/catalog/products/')
