import logging

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from django.dispatch import receiver

logger = logging.getLogger(__name__)


def do_login(request):
    user_login = request.POST.get('username', 'none')
    user = authenticate(username=user_login,
                        password=request.POST.get('password', 'none'))
    if user is not None:
        login(request, user)
        return True, "ok"
    else:
        return False, "login_failed"


def do_logout(request):
    if request.user.is_authenticated:
        logout(request)
        return True, "logout"
    return False, "logout_failed"


# code that put in logs every successful and problematic login/logout event
# https://stackoverflow.com/questions/37618473/how-can-i-log-both-successful-and-failed-login-and-logout-attempts-in-django
@receiver(user_logged_in)
def user_logged_in_callback(sender, request, user, **kwargs):
    # to cover more complex cases:
    # http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
    ip = request.META.get('REMOTE_ADDR')
    logger.info('login user: {user} via ip: {ip}'.format(
        user=user,
        ip=ip
    ))


@receiver(user_logged_out)
def user_logged_out_callback(sender, request, user, **kwargs):
    ip = request.META.get('REMOTE_ADDR')

    logger.info('logout user: {user} via ip: {ip}'.format(
        user=user,
        ip=ip
    ))


@receiver(user_login_failed)
def user_login_failed_callback(sender, credentials, **kwargs):
    logger.warning('login failed for: {credentials}'.format(
        credentials=credentials,
    ))