try:
    from urllib.parse import urlparse
except ImportError:  # Python2
    from urlparse import urlparse  # noqa

import django

from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login
try:
    from django.contrib.sites.shortcuts import get_current_site
except ImportError:
    from django.contrib.sites.models import get_current_site
from django.shortcuts import redirect
from django.template.response import TemplateResponse as BaseTemplateResponse
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters

from .forms import AuthenticationForm


class TemplateResponse(BaseTemplateResponse):
    def __init__(self, request, template, context=None, **kwargs):
        if django.VERSION < (1, 8):
            kwargs['current_app'] = request.current_app
        super(TemplateResponse, self).__init__(
            request, template, context=context, **kwargs)


@sensitive_post_parameters()
@csrf_protect
@never_cache
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(data=request.POST, request=request)
        if form.is_valid():
            netloc = urlparse(redirect_to)[1]

            # Use default setting if redirect_to is empty
            if not redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Heavier security check -- don't allow redirection to a different
            # host.
            elif netloc and netloc != request.get_host():
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security checks complete. Log the user in.
            auth_login(request, form.get_user())

            return redirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    request.current_app = current_app
    return TemplateResponse(request, template_name, context)
