from django.contrib import messages
from django.db.models import Q
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

import json
import logging

from lazysignup.decorators import allow_lazy_user
from account.decorators import login_required

from procat2.models import Catalog, Season, Region

log = logging.getLogger(__name__)


@login_required
def catalogedit(request, id=0):
    regions = Region.objects.order_by('ordering')
    seasons = Season.objects.order_by('ordering')
    context = {
        'catalogID': id,
        'regions': [r.serialize() for r in regions if r.visible],
        'seasons': [s.serialize() for s in seasons][::-1], # reversed
    }
    return render(request, 'catalogedit/catalogedit.html', context)


@login_required
def get_catalog(request, id):
    cat = get_object_or_404(Catalog, Q(id=id) & (Q(owner=request.user) | Q(public=True)))
    prods = cat.products()
    return JsonResponse({
        'catalog': cat.data,
        'products': [p.serialize() for p in prods],
    })


@csrf_exempt
@login_required
@require_http_methods(["POST"])
def save_catalog(request):
    body = request.body
    if not body or len(body) < 1:
        return HttpResponse('Bad request: no data', status=400)

    data = json.loads(body.decode('utf-8'))

    id = data.get('id')

    if id:
        try:
            cat = Catalog.objects.get(id=id)

            if cat.owner == request.user:
                log.debug('saving existing catalog, id {}'.format(id))
            else:
                log.debug('copying public catalog, id {}'.format(id))
                cat = Catalog(owner=request.user, season=cat.season, region=cat.region)
        except ObjectDoesNotExist:
            raise Http404("Catalog not found")
    else:
        season = Season.objects.get(id=data.get('season'))
        region = Region.objects.get(id=data.get('region'))
        cat = Catalog(owner=request.user, season=season, region=region)
        log.debug('saving new catalog, season {}, region {}'.format(season, region))

    cat.data = data
    cat.data['owner'] = cat.owner.id
    cat.update_metadata()
    cat.save()

    # update id in json data and resave
    # in case new catalog or copied catalog
    cat.data['id'] = cat.id
    cat.save()

    cat.queue_render()

    return JsonResponse(cat.data, safe=False)
