"""When you get an error email from your Django app telling you someone got a
server error, it’s not always easy to tell which user had a problem.
It might help your debugging to know or you might want to contact the user to
tell them you have fixed the problem."""

from django.conf import settings
from django.contrib import auth
from django.contrib.sessions.models import Session
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    """Management command to find the right user to a session."""
    help = 'If the session still exists find it and show the related User'

    def add_arguments(self, parser):
        """add commandline parameters to ban or delete the user."""
        # Positional arguments
        parser.add_argument('session_id_list', nargs='+', type=str)

        # Named (optional) arguments
        parser.add_argument(
            '--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete the Useraccount'
        )

        parser.add_argument(
            '--ban',
            action='store_true',
            dest='ban',
            default=False,
            help='Ban the Useraccount'
        )

    def handle(self, *args, **options):
        """Try to find the users that belong to the given session_ids.
        delete or ban them if parametes had been set."""
        for session_id in options['session_id_list']:
            try:
                session = Session.objects.get(session_key=session_id)
                uid = session.get_decoded().get('_auth_user_id')
                user = auth.get_user_model().objects.get(pk=uid)
            except Session.DoesNotExist:
                self.stderr.write('Session "%s" does not exist' % session_id)
                continue
            except settings.AUTH_USER_MODEL.DoesNotExist:
                self.stderr.write(
                    'Session "%s" has no registed User' % session_id)
                continue
            if options['delete']:
                self.stdout.write('deleting %s' % user.username)
                user.delete()
            elif options['ban']:
                self.stdout.write('banning %s' % user.username)
                user.is_active = False
                user.save()
            else:
                self.stdout.write("Username: %s" % user.username)
