from django.db import models
from django.utils.translation import gettext_lazy as _
from taggit.managers import TaggableManager


from .episode import Episode
from .sound import Sound


__all__ = ("Track",)


class Track(models.Model):
    """Track of a playlist of an object.

    The position can either be expressed as the position in the playlist
    or as the moment in seconds it started.
    """

    episode = models.ForeignKey(
        Episode,
        models.CASCADE,
        blank=True,
        null=True,
        verbose_name=_("episode"),
    )
    sound = models.ForeignKey(
        Sound,
        models.CASCADE,
        blank=True,
        null=True,
        verbose_name=_("sound"),
    )
    position = models.PositiveSmallIntegerField(
        _("order"),
        default=0,
        help_text=_("position in the playlist"),
    )
    timestamp = models.PositiveSmallIntegerField(
        _("timestamp"),
        blank=True,
        null=True,
        help_text=_("position (in seconds)"),
    )
    title = models.CharField(_("title"), max_length=128)
    artist = models.CharField(_("artist"), max_length=128)
    album = models.CharField(_("album"), max_length=128, null=True, blank=True)
    tags = TaggableManager(verbose_name=_("tags"), blank=True)
    year = models.IntegerField(_("year"), blank=True, null=True)
    # FIXME: remove?
    info = models.CharField(
        _("information"),
        max_length=128,
        blank=True,
        null=True,
        help_text=_(
            "additional informations about this track, such as " "the version, if is it a remix, features, etc."
        ),
    )

    class Meta:
        verbose_name = _("Track")
        verbose_name_plural = _("Tracks")
        ordering = ("position",)

    def __str__(self):
        return "{self.artist} -- {self.title} -- {self.position}".format(self=self)

    def save(self, *args, **kwargs):
        if (self.sound is None and self.episode is None) or (self.sound is not None and self.episode is not None):
            raise ValueError("sound XOR episode is required")
        super().save(*args, **kwargs)
