import json

from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import redirect, render

from .models import Game2048

# Create your views here.

# test_user
# 8!S#5RP!WVMACg


def game(request):

    return render(request, 'game_2048/index.html')


def set_result(request):
    user = request.user if str(
        request.user) != "AnonymousUser" else User.objects.get(username='test_user')

    if request.method == 'POST':
        # Get the game state from the POST request
        game_state = request.body

        obj = Game2048.objects.get(user=user)

        # Check if the game state idendical to the server game state
        if game_state != obj.game_state:
            # let string to JSON object
            json_game_state = json.loads(game_state)
            # extract value of best from JSON objest
            obj.best_score = json_game_state['best']
            obj.game_state = json_game_state  # save JSON object to game_state
            obj.save()
    else:
        return redirect('game_2048:game')

    return JsonResponse("", safe=False)


def get_result(request):
    # Check if user is logged in if not set user to test_user
    user = request.user if str(
        request.user) != "AnonymousUser" else User.objects.get(username='test_user')

    if request.method == 'GET':
        obj, created = Game2048.objects.get_or_create(user=user)
        game_state = obj.game_state

    return JsonResponse(game_state, safe=False)

[((260, 299), 'django.shortcuts.render', 'render', (['request', '"""game_2048/index.html"""'], {}), "(request, 'game_2048/index.html')\n", (266, 299), False, 'from django.shortcuts import redirect, render\n'), ((1086, 1114), 'django.http.JsonResponse', 'JsonResponse', (['""""""'], {'safe': '(False)'}), "('', safe=False)\n", (1098, 1114), False, 'from django.http import JsonResponse\n'), ((1467, 1503), 'django.http.JsonResponse', 'JsonResponse', (['game_state'], {'safe': '(False)'}), '(game_state, safe=False)\n', (1479, 1503), False, 'from django.http import JsonResponse\n'), ((405, 443), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': '"""test_user"""'}), "(username='test_user')\n", (421, 443), False, 'from django.contrib.auth.models import User\n'), ((1047, 1073), 'django.shortcuts.redirect', 'redirect', (['"""game_2048:game"""'], {}), "('game_2048:game')\n", (1055, 1073), False, 'from django.shortcuts import redirect, render\n'), ((1282, 1320), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': '"""test_user"""'}), "(username='test_user')\n", (1298, 1320), False, 'from django.contrib.auth.models import User\n'), ((791, 813), 'json.loads', 'json.loads', (['game_state'], {}), '(game_state)\n', (801, 813), False, 'import json\n')]