from django.contrib import admin
from django.utils.safestring import mark_safe

from soft_sun_26825 import settings

from . import models
from .models import Profile, UserLikeDislikeCount


class MediaInline(admin.StackedInline):
    model = models.Media


@admin.register(models.Artist)
class ArtistAdmin(admin.ModelAdmin):
    list_display = search_fields = ("stage_name", "email", "avatar")
    readonly_fields = ('total_followers',)

    def total_followers(self, obj):
        return obj.user.followers.all().count()

    def email(self, obj):
        return obj.user.email

    def get_queryset(self, request):
        return super().get_queryset(request).filter(user__user_type="artist")

    def avatar(self, obj):
        img_url = 'https://via.placeholder.com/50'
        if obj.profile_picture:
            img_url = obj.profile_picture.url

        return mark_safe(f"<img src='{img_url}' width='50' height='50' />")


@admin.register(models.Fan)
class FanAdmin(admin.ModelAdmin):
    list_display = search_fields = ["full_name", "email", "artists_followed", "avatar"]
    readonly_fields = ('artists_followed',)

    # def artists_followed(self, obj):
    #     return obj.user.followers.all().count()

    def email(self, obj):
        return obj.user.email

    def full_name(self, obj):
        return obj.user.get_full_name()

    def artists_followed(self, obj):
        followed = ", ".join([artist.profile.stage_name for artist in obj.user.followed.all()])
        return mark_safe(f"{followed}")

    def get_queryset(self, request):
        return super().get_queryset(request).filter(user__user_type="fan")

    def has_add_permission(self, request, *args, **kwargs):
        return False

    def avatar(self, obj):
        if obj.profile_picture:
            profile_img_url = obj.profile_picture.url
            img_url = f'{profile_img_url}'
        else:
            img_url = 'https://via.placeholder.com/50'

        return mark_safe(f"<img src='{img_url}' width='50' height='50' />")


class MediaCommentInline(admin.StackedInline):
    model = models.MediaComment


@admin.register(models.Media)
class MediaAdmin(admin.ModelAdmin):
    list_display = ("song_name", "owner", "uid", "duration", "_likes", "_dislikes")
    inlines = [MediaCommentInline]

    def _likes(self, obj):
        return obj.likes.all().count()

    def _dislikes(self, obj):
        return obj.dislikes.all().count()


class ProfileAdmin(admin.ModelAdmin):
    models = Profile
    list_display = ["user", "arts", "song_name", "stage_name"]
    search_fields = ["stage_name"]


class UserLikeDislikeCountAdmin(admin.ModelAdmin):
    list_display = ["user", "like_counter", "dislike_counter", "profile"]


admin.site.register(Profile, ProfileAdmin)
admin.site.register(UserLikeDislikeCount, UserLikeDislikeCountAdmin)
