from django.urls import reverse
from django.shortcuts import redirect
from django.contrib import admin

from scrobbles.models import (
    AudioScrobblerTSVImport,
    ChartRecord,
    KoReaderImport,
    LastFmImport,
    RetroarchImport,
    Scrobble,
)
from scrobbles.mixins import ScrobblableItem
from scrobbles.mixins import Genre


class ScrobbleInline(admin.TabularInline):
    model = Scrobble
    extra = 0
    raw_id_fields = (
        "item",
        "user",
    )
    exclude = (
        "scrobble_log",
        "timezone",
        "videogame_save_data",
        "screenshot",
    )
    fk_name = "item"


class ImportBaseAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = (
        "uuid",
        "process_count",
        "processed_finished",
        "processing_started",
    )
    ordering = ("-created",)


@admin.register(AudioScrobblerTSVImport)
class AudioScrobblerTSVImportAdmin(ImportBaseAdmin):
    ...


@admin.register(LastFmImport)
class LastFmImportAdmin(ImportBaseAdmin):
    ...


@admin.register(KoReaderImport)
class KoReaderImportAdmin(ImportBaseAdmin):
    ...


@admin.register(RetroarchImport)
class RetroarchImportAdmin(ImportBaseAdmin):
    ...


@admin.register(Genre)
class GenreAdmin(admin.ModelAdmin):
    list_display = (
        "name",
        "source",
    )


@admin.register(ChartRecord)
class ChartRecordAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = (
        "user",
        "rank",
        "count",
        "year",
        "week",
        "month",
        "day",
        "media_name",
    )
    ordering = ("-created",)

    def media_name(self, obj):
        return obj.media_obj


@admin.register(Scrobble)
class ScrobbleAdmin(admin.ModelAdmin):
    date_hierarchy = "timestamp"
    list_display = (
        "timestamp",
        "item_title",
        "media_type",
        "playback_percent",
        "source",
        "in_progress",
        "is_paused",
        "played_to_completion",
        "user",
    )
    readonly_fields = (
        "item_media_type",
    )
    raw_id_fields = (
        "item",
    )
    list_filter = (
        "is_paused",
        "in_progress",
        "media_type",
        "source",
        "timezone",
        "user",
    )
    ordering = ("-timestamp",)

    def item_title(self, obj):
        return obj.media_obj

    def item_media_type(self, obj):
        return obj.media_type

    def playback_percent(self, obj):
        return obj.percent_played

    def get_queryset(self, request):
        qs = super().get_queryset(request).exclude(timestamp__year=None)
        return qs

@admin.register(ScrobblableItem)
class ScrobblableItemAdmin(admin.ModelAdmin):
    list_display = (
        "title",
        "get_media_type",
    )
