from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.views import generic
from asset.models import Asset
from django.shortcuts import get_object_or_404, reverse
from django.http import HttpResponse, HttpResponseRedirect


class AssetCreateView(CreateView):
    model = Asset
    fields = ['named_id', 'description', 'quantity']

    def form_valid(self, form):
        if not form.instance.named_id.startswith('A-'):
            form.instance.named_id = 'A-' + form.instance.named_id
        form.instance.changed_by = self.request.user
        form.instance.created_by = self.request.user
        return super().form_valid(form)


class AssetUpdateView(UpdateView):
    model = Asset
    fields = ['named_id', 'description', 'quantity']
    success_url = '/asset/'

    def form_valid(self, form):
        if not form.instance.named_id.startswith('A-'):
            form.instance.named_id = 'A-' + form.instance.named_id
        form.instance.changed_by = self.request.user
        return super().form_valid(form)


class AssetDeleteView(DeleteView):
    model = Asset
    success_url = reverse_lazy('asset:list')


class AssetListView(generic.ListView):
    template_name = 'asset/asset_list.html'
    context_object_name = 'asset_list'
    model = Asset
    paginate_by = 20

    """
    def get_queryset(self):
        # Return the last 20 created containers
        return Asset.objects.order_by('-created_ts')[:20]
    """


def asset_save(request, asset_id):
    asset = get_object_or_404(Asset, pk=asset_id)
    asset.description = request.POST['description']
    asset.quantity = request.POST['quantity']
    asset.save();
    return HttpResponseRedirect(reverse('asset:list'))


def asset_from_gtin(request):
    from .gtin_service import get_by_gtin
    gtin = request.POST['gtin']
    print(f'Try gtin={gtin}')
    product = get_by_gtin(gtin)
    if product is None:
        print(f'ERROR: Could not create asset for gtin={gtin}')
    else:
        print(f'Create new product: {product.name}, brand={product.brand}, gtin={product.gtin}')
        asset = Asset.objects.create(
            named_id='A-' + product.gtin,
            description=product.name,
            created_by=request.user,
            changed_by=request.user)
        asset.save()
    return HttpResponseRedirect(reverse('asset:list'))
