from django.db import models


class Platform(models.Model):
    slug = models.SlugField()
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Download(models.Model):
    slug = models.SlugField()
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class VersionManager(models.Manager):
    def get_latest(self, download, platform):
        if isinstance(download, str):
            try:
                download = Download.objects.get(slug=download)
            except Download.DoesNotExist:
                return None

        if isinstance(platform, str):
            try:
                platform = Platform.objects.get(slug=platform)
            except Platform.DoesNotExist:
                return None

        latest = (Version.objects
                  .filter(platform=platform, download=download)
                  .filter(available=True)
                  .order_by('-latest', '-id')
                  .first())
        if not latest:
            return None

        return latest

class Version(models.Model):
    download = models.ForeignKey(Download, on_delete=models.CASCADE, db_index=True)
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE, db_index=True)
    version = models.CharField(max_length=50)
    latest = models.BooleanField(default=False, blank=True)
    available = models.BooleanField(default=True, blank=True)
    url = models.URLField()

    objects = VersionManager()

    def save(self, *args, **kwargs):
        if self.latest:
            # Unmark as latest any other version for this download/platform
            latest = Version.objects.filter(platform=self.platform, download=self.download, latest=True)
            for k in latest:
                k.latest = False
                k.save()

        super().save(*args, **kwargs)

    def __str__(self):
        return "%s v%s for %s" % (self.download, self.version, self.platform)
