from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import PlayerCard
from .cards import PlayerCardService


class MyPlayerCardsView(APIView):
    permission_classes = [IsAuthenticated]
    http_method_names = ["get", "head", "options"]

    def get(self, request, card_id=None):
        cards = PlayerCard.objects.select_related("player", "player__career").filter(
            Q(owner=request.user) | Q(player__career__user=request.user)
        ).order_by("-created_at")
        if card_id is not None:
            card = get_object_or_404(cards, pk=card_id)
            return Response(self.snapshot(card))
        return Response({"cards": [self.snapshot(card) for card in cards[:100]]})

    @staticmethod
    def snapshot(card):
        return {"id": str(card.pk), "player_id": str(card.player_id), "status": card.status,
                "predecessor_id": str(card.predecessor_id) if card.predecessor_id else None,
                "chain": card.chain, "mint_address": card.mint_address,
                "issuance_status": "MINTED" if card.mint_address else "NOT_MINTED",
                "owner_id":str(card.owner_id), "rights":PlayerCardService.rights(card),
                "mint_manifest":PlayerCardService.mint_manifest(card),
                "metadata_hash": card.metadata_hash, "metadata": PlayerCardService.metadata(card)}
