from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import redirect, render
from django.utils.translation import gettext as _

from .forms import RedirectForm
from .models import Redirect


def go(request, name):
    try:
        obj = Redirect.objects.get(name=name)
    except Redirect.DoesNotExist:
        if request.user.has_perm("redirect.add_redirect"):
            return redirect("redirect:manage", name=name)

        raise Http404()

    return redirect(obj)


@login_required
def manage(request, name):
    try:
        obj = Redirect.objects.get(name=name)
    except Redirect.DoesNotExist:
        obj = None

    form = RedirectForm(instance=obj)

    if request.method == "POST":
        form = RedirectForm(request.POST, instance=obj)

        if form.is_valid():
            action = "add" if obj is None else "change"
            if request.user.has_perm(f"redirect.{action}_redirect"):
                obj = form.save(commit=False)

                if action == "add":
                    obj.name = name
                    obj.owner = request.user

                obj.save()

                messages.success(
                    request,
                    _(
                        "Successfully %s redirect"
                        % ("added" if action == "add" else "changed")
                    ),
                )
            else:
                messages.error(
                    request, _(f"You do not have permission to {action} this redirect.")
                )

                return redirect("redirect:manage", name=name)
        else:
            return redirect("redirect:manage", name=name)

    return render(
        request,
        "redirect/manage.html",
        {"form": form, "name": name, "new": obj is None},
    )
