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

from .models import Asset
from dashboard.models import AssetImportRequest


class AssetImportRequestInline(admin.TabularInline):
    model = AssetImportRequest
    fk_name = 'asset'
    readonly_fields = ('resolved', 'failed', )
    extra = 0
    show_change_link = True
    can_delete = False

    def get_fields(self, request, obj=None):
        return self.get_readonly_fields(request, obj)

class AssetAdmin(admin.ModelAdmin):
    search_fields = ('platform_identifier', 'uuid')
    list_display = ('uuid', 'internal_type', 'platform_identifier', 'content_type')
    list_filter = ('platform', 'internal_type', 'source_environment')
    raw_id_fields = ('owner', 'supersedes')
    readonly_fields = ('get_url', 'is_superseded', 'superseded_by')
    inlines = (AssetImportRequestInline, )

    def get_url(self, instance):
        return mark_safe('<a href="{url}">{url}</a> or <a href="{url}" download>download</a>'.format(url=instance.get_url()))
    get_url.short_description = 'URL'
    def is_superseded(self, instance):
        return 'Yes' if instance.is_superseded() else 'No'
    is_superseded.short_description = 'Is superseded'
    def superseded_by(self, instance):
        try:
            return Asset.objects.get(supersedes=instance.uuid)
        except Exception as e:
            return 'Not found'
        else:
            

    superseded_by.short_description = 'Superseded by'

admin.site.register(Asset, AssetAdmin)

return None