from rest_framework import serializers
from .models import Calendar, Event, Organization, Promo

from django.db import models
from django.contrib.auth.models import User
from rest_framework.permissions import BasePermission

class ScopesPermission(BasePermission):
    scopes_map = {
        'admin': [],
        'platinum': ['gold', 'silver', 'free'],
        'gold': ['silver', 'free'],
        'silver': ['free'],
        'free': [],
    }

    def has_permission(self, request, view):
        if not request.user.is_authenticated:
            return False

        # Check if the user has an associated scope
        try:
            user_scope = UserScope.objects.get(user=request.user)
        except UserScope.DoesNotExist:
            return False

        # Check if the user's scope has the required permission level
        if user_scope.scope not in self.scopes_map:
            return False

        allowed_scopes = self.scopes_map[user_scope.scope]
        return request.scope in allowed_scopes or request.scope == user_scope.scope

############
## Events ##
############


class OrganizationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organization
        fields = ('id', 'name', 'website', 'city', 'latitude', 'longitude', 'has_map')
        # fields = '__all__'


class EventSerializer(serializers.ModelSerializer):
    venue = OrganizationSerializer(many=False)
    event_type = serializers.CharField(source='get_event_type_display')
    # target_language = serializers.SerializerMethodField()
    class Meta:
        model = Event
        fields = '__all__'
        depth = 2
#        fields = ('id', 'name',)

class CalSerializer(serializers.ModelSerializer):
    events_count = serializers.SerializerMethodField()
    class Meta:
        model = Calendar
        fields = ['id', 'name', 'shortcode', 'events_count', 'published']
        # fields = '__all__'
    

    def get_events_count(self, obj):
        # obj is the current Tag instance
        return obj.events.count() 

class PromoSerializer(serializers.ModelSerializer):
    organization = OrganizationSerializer(many=False)
    promo_emoji = serializers.CharField(source='get_promo_type_display')
    # event_type = serializers.CharField(source='get_event_type_display')
    class Meta:
        model = Promo
        fields = ('id', 'title', 'organization', 'promo_type', 'long_text', 'short_text', 'promo_image', 'target_link', 'promo_emoji')
        # fields = '__all__'
        depth = 2