from cards.models import Card
from django.core.exceptions import PermissionDenied

class TradeOfferContextMixin:
    def get_context_data(self, **kwargs):
        # Start with any context passed in.
        context = kwargs.copy()
        # Include available cards requirements for multiselect fields.
        context.setdefault("cards", Card.objects.all().order_by("name", "rarity_level"))
        
        # Provide friend_codes and selected_friend_code as in TradeOfferCreateView
        friend_codes = self.request.user.friend_codes.all()
        context["friend_codes"] = friend_codes
        
        if "initiated_by" in self.request.GET:
            try:
                selected_friend_code = friend_codes.get(pk=self.request.GET.get("initiated_by"))
            except friend_codes.model.DoesNotExist:
                selected_friend_code = self.request.user.default_friend_code or friend_codes.first()
        else:
            selected_friend_code = self.request.user.default_friend_code or friend_codes.first()
        context["selected_friend_code"] = selected_friend_code
        
        return context 

class FriendCodeRequiredMixin:
    """
    Mixin to ensure the authenticated user has at least one friend code.
    This mixin must be placed after LoginRequiredMixin in the view's inheritance order.
    """
    def dispatch(self, request, *args, **kwargs):
        # Since LoginRequiredMixin guarantees that request.user is authenticated,
        # we assume request.user has the attribute `friend_codes`. If no friend code exists,
        # raise a PermissionDenied error.
        if not getattr(request.user, 'friend_codes', None) or not request.user.friend_codes.exists():
            raise PermissionDenied("No friend codes available for your account.")
        return super().dispatch(request, *args, **kwargs) 