# Standard Library
import random

# Django
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import get_user_model, logout as django_logout
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse

# Localfolder
from .giphy import gif_random
from .models import Game


# Create your views here.

def index(request):
    """
    This is the index view. That is all.
    """
    return render(request, 'game/index.html')


def new_game(request):
    """
    This view creates a new game token when a user clicks on "New Game" button on index.html
    This is done randomly and then checks in the database to see if that token is already present.
    If so, it'll keep on trying until it finds a unique token.
    """
    # Makes initial token
    new_token = str(random.randint(1000, 9999))
    # Checks to see if the token created is unique
    # What if ALL tokens already taken? Well, that would suck!
    while Game.objects.filter(token=new_token).exists():
        new_token = str(random.randint(1000, 9999))
    # Make new game in database with the token
    g = Game(token=new_token)
    g.save()
    request.session['game_mode'] = request.POST['game_mode']
    return HttpResponseRedirect(reverse('game:pre_game_room', args=(new_token,)))


def join_game(request):
    """
    This view allows a different users to join a pre-exisiting game if it exists.
    If it exists, it should also check to see if the user is still able to join the game.
    """
    token = request.POST["join_token"]
    # Check to see if game corresponding to game token exists
    # An AND statement to check to see if the game is already "closed" should be added here
    if Game.objects.filter(token=token).exists():
        return HttpResponseRedirect(reverse('game:pre_game_room', args=(token,)))
    messages.error(request, "Token not found or invalid.")
    return render(request, 'game/index.html', status=302)


def pre_game_room(request, token):
    """
    This is where players come to wait until the game can start
    """
    return render(request, 'game/pre_game_room.html', {"token": token})


def start_game(request, token):
    """
    The game is initiated through this view, not actually displayed though
    """
    current_game = Game.objects.get(token=token)
    current_game.game_active = True
    current_game.save()

    return HttpResponseRedirect(reverse('game:game_lobby', args=(token,)))


# ==================
def hotseat_gameplay(request, token):
    # if roundnumber of game is 1 (first turn)
    g = Game.objects.get(token=token)
    if g.current_round == 4:
        print(g.gameround_set.all())
        return render(request, 'game/hotseat_results.html', {"results": g.gameround_set.all()})
    if g.current_round > 1:
        received_gif = g.gameround_set.get(round_number=g.current_round - 1).giphy_url
    else:
        received_gif = ""
    try:
        # g.gameround_set.get(round_number=g.current_round)
        gif = g.gameround_set.get(round_number=g.current_round).giphy_url
        phrase = g.gameround_set.get(round_number=g.current_round).user_text
        context = {
            'token': token,
            'game': g,
            'gif': gif,
            'phrase': phrase,
            'received_gif': received_gif
        }
    except:
        gif = "http://media0.giphy.com/media/YJBNjrvG5Ctmo/giphy.gif"
        context = {
            'token': token,
            'game': g,
            'gif': gif,
            'received_gif': received_gif
        }
    return render(request, 'game/hotseat_gameplay.html', context)


# Not sure what this is for..? \/\/\/
# def select_phrase(request, token):
#     phrase = request.POST['phrase']


def choose_new_gif(request, token):
    response = gif_random(tag=request.POST['phrase'])
    try:
        gif = response.json()['data']['image_url']
    except TypeError:
        #messages.add_message(request, messages.ERROR, 'The phrase you entered could not produce a gif, please try something different.')
        messages.error(request, 'The phrase you entered could not produce a gif, please try something different.')
        return HttpResponseRedirect(reverse('game:game_lobby', args=(token,)))


    g = Game.objects.get(token=token)
    try:
        g_round = g.gameround_set.get(round_number=g.current_round)
        g_round.user_text = request.POST['phrase']
        g_round.giphy_url = gif
        g_round.save()
    except:
        g.gameround_set.create(round_number=g.current_round,
                               user_text=request.POST['phrase'],
                               giphy_url=gif)
        g.save()

    return HttpResponseRedirect(reverse('game:game_lobby', args=(token,)))


def pass_on(request, token):
    g = Game.objects.get(token=token)
    print(g.current_round)
    g.current_round += 1
    print(g.current_round)
    g.save()

    return HttpResponseRedirect(reverse('game:game_lobby', args=(token,)))


def _login_user(request, user):
    """
    Log in a user without requiring credentials (using ``login`` from
    ``django.contrib.auth``, first finding a matching backend).

    """
    from django.contrib.auth import load_backend, login
    if not hasattr(user, 'backend'):
        for backend in settings.AUTHENTICATION_BACKENDS:
            if user == load_backend(backend).get_user(user.pk):
                user.backend = backend
                break
    if hasattr(user, 'backend'):
        return login(request, user)


def choose_name(request):
    User = get_user_model()
    username = request.POST['username']
    try:
        user = User.objects.create(username=username)
        if request.user.is_authenticated():
            old_user = request.user
            django_logout(request)
            old_user.delete()
        _login_user(request, user)
        messages.success(request, 'You have chosen "{}"!'.format(username))
    except IntegrityError:
        messages.error(request, 'Sorry, "{}" is already taken :('.format(username))

    return redirect(request.GET.get('next', '/'))

@@ -4311,17 +4311,16 @@
 en,)))%0A%0A
-%0A
     g = 
@@ -4353,163 +4353,67 @@
 en)%0A
-    try:%0A        g_round = g.gameround_set.get(round_number=g.current_round)%0A        g_round.user_text = request.POST%5B'phrase'%5D%0A        g_round.giphy_url =
+%0A    # If there is already a gif, update, otherwise get new
  gif
@@ -4421,19 +4421,18 @@
     
-   
+g,
  g_round
 .sav
@@ -4431,59 +4431,53 @@
 ound
-.save()%0A    except:%0A        g.gameround_set.create(
+ = g.gameround_set.update_or_create(%0A        
 roun
@@ -4502,39 +4502,16 @@
 _round,%0A
-                       
         
@@ -4544,39 +4544,16 @@
 rase'%5D,%0A
-                       
         
@@ -4570,25 +4570,8 @@
 gif)
-%0A        g.save()
 %0A%0A  

refactor get new gif