import traceback

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

from .forms import *
from django.contrib.auth.decorators import login_required


def orders_list(request):
    if request.user.is_authenticated:
        orders = Order.get_all_for_user(request.user)
        return render(request, 'orders/orders-list.html', {'orders': orders[:50]})
    else:
        return HttpResponseRedirect('/accounts/register')


def order_create(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            order = Order(owner=request.user)
            form = BaseOrderCreationForm(request.POST, instance=order)
            if form.is_valid():
                form.save()
                # сохраним файлы
                files = request.FILES.getlist('images')
                for img in files[:OrderImage.MAX_IMAGES]:
                    OrderImage(order=order, image=img).save()
                return HttpResponseRedirect('/orders/')
        else:
            form = BaseOrderCreationForm()
    else:
        if request.method == 'POST':
            order = Order()
            form = UnregisteredUserOrderCreationForm(request.POST, instance=order)
            if form.is_valid():
                form.save()
                # сохраним файлы
                files = request.FILES.getlist('images')
                for img in files[:OrderImage.MAX_IMAGES]:
                    OrderImage(order=order, image=img).save()
                return HttpResponseRedirect('/dev')
        else:
            form = UnregisteredUserOrderCreationForm()

    return render(request, 'orders/order-create.html', {'form': form})


@login_required
def order_view(request, order_id):
    render_vars = {}
    try:
        order = Order.get_all_for_user(request.user)
        order = order.select_related('address_city').get(id=order_id)
        render_vars["order"] = order

        render_vars["images"] = OrderImage.objects.filter(order=order)

        render_vars["can_responde"] = order.owner_id != request.user.id

        if render_vars["can_responde"]:
            render_vars["respondes_count"] = OrderRespond.objects.filter(order_id=order_id).count()

        render_vars["is_responde"] = OrderRespond.objects.filter(user_id=request.user.id, order_id=order_id).count() > 0

        render_vars["respond_users"] = OrderRespond.objects.filter(order_id=order_id).\
            select_related('user').order_by('create_time')

    except Exception:
        traceback.print_exc()
        render_vars["order"] = None

    return render(request, 'orders/order-view.html', render_vars)


@login_required
def order_respond(request, order_id):
    try:
        if request.method == 'POST':
            action = None
            if "action" in request.POST:
                action = request.POST["action"]

            if action == "respond":
                r = OrderRespond(order_id=order_id, user=request.user)
                r.save()

            if action == "unrespond":
                OrderRespond.objects.filter(order_id=order_id, user=request.user).delete()

    except Exception:
        traceback.print_exc()

    return HttpResponseRedirect(f'/orders/view/{order_id}')
