"""Views for rolling dice."""
import json
import logging

from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes

from dice.roller import DiceRoller

logger = logging.getLogger(__name__)
roller = DiceRoller()


@api_view(['POST'])
@authentication_classes((BasicAuthentication, ))
@permission_classes((IsAuthenticated, ))
def rpc_roll_dice(request):
    """Get a dice string from the client, roll the dice, and give the result."""
    if request.method != 'POST':
        return Response({'detail': "Supported method: POST."}, status=405)

    try:
        roll_data = json.loads(request.body)
        dice_str = roll_data['dice']
    except (json.decoder.JSONDecodeError, KeyError):
        return Response({'detail': "Request must be JSON with a 'dice' parameter."}, status=400)

    try:
        result_str = roller.do_roll(dice_str)
        return Response({'dice': dice_str, 'result': result_str})
    except AssertionError as aex:
        return Response({'detail': f"Could not roll dice: {aex}", 'dice': dice_str}, status=400)
    except ValueError:
        return Response({'detail': f"Could not parse requested dice '{dice_str}'.", 'dice': dice_str}, status=400)