import json

from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, HttpResponse
from django.http import HttpResponseBadRequest, JsonResponse
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from bloonsa_game.models import Level, LevelRating, LevelScore
from users.models import Player
from users.util import bloonsa_util, actions


class CSRFexemptTemplateView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)


class LoadLevel(CSRFexemptTemplateView):
    def post(self, request, *args, **kwargs):
        level_id = request.POST.get("level_id")
        if level_id is None or not level_id.isdigit():
            return HttpResponseBadRequest()

        level: Level = Level.objects.filter(level_id=int(level_id)).first()
        if level is None:
            return HttpResponseBadRequest()

        if request.user.is_authenticated:
            bloonsa_util.tag_player(request=request)
            player: Player = Player.objects.get(user=request.user)
            player.bloonsa_levels_played.add(level)
            bloonsa_util.log(player=player,
                             action=actions.bloonsa_load_level_by_id,
                             note=level.level_id)

        flashVars = level.get_flash_vars(seperator="&")
        return HttpResponse(flashVars)


class RandomLevel(CSRFexemptTemplateView):
    def post(self, request, *args, **kwargs):
        level: Level = Level.objects.order_by("?").first()
        flashVars = level.get_flash_vars(seperator="&")

        if request.user.is_authenticated:
            bloonsa_util.tag_player(request=request)
            player: Player = Player.objects.get(user=request.user)
            level.played_by.add(player)
            bloonsa_util.log(player=player,
                             action=actions.bloonsa_load_random_level,
                             note=level.level_id)

        return HttpResponse(flashVars)

    def get(self, request, *args, **kwargs):
        return self.post(request=request, *args, **kwargs)


class CompleteLevel(CSRFexemptTemplateView):

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponse(content="GG", status=200)

        bloonsa_util.tag_player(request=request)
        level_id = int(request.POST.get("level_id"))
        darts_left = int(request.POST.get("darts_left"))
        pops = int(request.POST.get("pops"))

        level: Level = Level.objects.get(level_id=level_id)
        player: Player = Player.objects.get(user=request.user)

        prevScore = player.bloonsa_level_scores.first()
        if prevScore is None \
            or pops > prevScore.pops \
            or pops == prevScore.pops and darts_left > prevScore.darts_left:
            score = LevelScore.objects.create(level=level,
                                               clear=True,
                                               darts_left=darts_left,
                                               pops=pops)
            if prevScore:
                player.bloonsa_level_scores.remove(prevScore)

            player.bloonsa_level_scores.add(score)
            score.save()
            player.save()
            bloonsa_util.log(player=player,
                             action=actions.bloonsa_submit_score,
                             note=level.level_id)

        # Sending empty content means error in as3
        return HttpResponse(content="GG", status=200)

class RateLevel(CSRFexemptTemplateView):

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponse(content="OK", status=200)

        bloonsa_util.tag_player(request=request)
        rating = int(request.POST.get("rating"))
        level_id = int(request.POST.get("level_id"))
        level: Level = Level.objects.get(level_id=level_id)
        player: Player = Player.objects.get(user=request.user)
        ratingObject = player.bloonsa_level_ratings.filter(level=level).first()
        bloonsa_util.log(player=player,
                         action=actions.bloonsa_rate_level,
                         note=level.level_id)
        if ratingObject:
            ratingObject.rating = rating
            ratingObject.save()
            return HttpResponse(content="OK", status=200)

        rating = LevelRating.objects.create(level=level,
                                            rating=rating)
        player.bloonsa_level_ratings.add(rating)
        rating.save()
        player.save()
        return HttpResponse(content="OK", status=200)



class GetStatusData(CSRFexemptTemplateView):

    def post(self, request, *args, **kwargs):
        bloonsa_util.tag_player(request=request)
        level_id = int(json.loads(request.body).get("level_id"))
        level = Level.objects.get(level_id=level_id)
        player = Player.objects.get(user=request.user)
        total_levels = Level.objects.count()
        level_cleared = player.has_beaten_bloonsa_level(level=level)

        jdata = {
            "bloonsa_levels_played": player.bloonsa_levels_played_count,
            "bloonsa_levels_beaten": player.bloonsa_levels_beaten_count,
            "bloonsa_total_levels": total_levels,

            "level_author_name": level.author.name,
            "level_author_id": level.author.id,
            "level_title": level.title,
            "level_id": level.level_id,
            "level_legacy_plays": level.plays,
            "level_plays": level.play_count,
            "level_rating": level.rating,
            "level_cleared": level_cleared,
        }
        return JsonResponse(jdata)