from django.db import models
from PodcastPlatform import settings
from audiofield.fields import AudioField
import os.path


class Podcast(models.Model):
    podcast_title = models.CharField(max_length=250)
    podcast_presenter = models.ForeignKey('auth.User', blank=True, null=True)
    genre = models.CharField(max_length=250)
    podcast_logo = models.ImageField(upload_to='image/', blank=True, null=True)
    desc = models.CharField(max_length=500, default='No description.')

    def __str__(self):
        return self.podcast_title


class PodcastPart(models.Model):
    podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE)
    file = AudioField(upload_to='media/', null=True, blank=True, ext_whitelist=(".mp3", ".wav", ".ogg"),
                      help_text="Allowed type - .mp3, .wav, .ogg")
    part_title = models.CharField(max_length=250)
    is_favourite = models.BooleanField(default=False)
    track_list = models.CharField(max_length=1000, default='No tracklist.')

    def audio_file_player(self):
        """audio player tag for admin"""
        if self.audio_file:
            file_url = settings.MEDIA_URL + str(self.audio_file)
            player_string = '<ul class="playlist"><li style="width:250px;">\
            <a href="%s">%s</a></li></ul>' % (file_url, os.path.basename(self.audio_file.name))
            return player_string

    audio_file_player.allow_tags = True
    audio_file_player.short_description = 'Audio file player'

    def __str__(self):
        return self.part_title


class UserFavourite(models.Model):
    user = models.ForeignKey('auth.User', unique=False)
    podcast = models.ForeignKey(Podcast, unique=False)

    def __unicode__(self):
        return self.user.username


class UserProfile(models.Model):
    user = models.ForeignKey('auth.User', unique=True)
    favorites = models.ManyToManyField(Podcast, related_name='favorited_by')

