from django.core.management.base import BaseCommand

from assets.models import Asset
from podcasts.models import PodcastEpisode


class Command(BaseCommand):
    help = 'Cleans up dangling references to superseded files on eps awaiting import'

    def handle(self, *args, **options):
        eps = PodcastEpisode.objects.filter(awaiting_import=True)
        for ep in eps:
            helped = False
            if ep.audio.is_superseded():
                new_audio = Asset.objects.filter(supersedes=ep.audio)[0]
                ep.audio = new_audio
                helped = True
            if ep.artwork.is_superseded():
                artworks = Asset.objects.filter(supersedes=ep.artwork)
                if artworks.count() == 1:
                    new_artwork = artworks[0]
                elif ep.podcast.cover_art.supersedes == ep.artwork:
                    new_artwork = ep.podcast.cover_art
                else:
                    new_artwork = None
                ep.artwork = None
                helped = True

            if helped:
                ep.awaiting_import = False
                ep.save()
