from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User

from pytils.translit import slugify

from storages.backends.s3boto3 import S3Boto3Storage

from .utils import asset_upload


READY = 'ready'
PROGRESS = 'progress'
FAIL = 'fail'
STATUS_CHOICES = (
    (READY, 'Ready'),
    (PROGRESS, 'Progress'),
    (FAIL, 'Fail'),
)


class BaseModel(models.Model):
    updated = models.DateTimeField(_('updated'), auto_now=True, db_index=True)
    created = models.DateTimeField(_('created'), auto_now_add=True, db_index=True)

    class Meta:
        abstract = True


class Category(models.Model):
    name = models.CharField('name', max_length=255, db_index=True)

    def __str__(self):
        return self.name


class Video(BaseModel):
    title = models.CharField(_('title'), max_length=255)
    slug = models.SlugField(_('slug'), max_length=255, unique=True, blank=True)
    description = models.TextField(_('description'), blank=True, null=True)
    local_file = models.FileField(
        _('local file'),
        upload_to='videos',
        blank=True,
        null=True,
    )
    s3_file = models.FileField(
        _('AWS S3 file'),
        storage=S3Boto3Storage(bucket_name='clutchpoints-videos'),
        blank=True,
        null=True,
        max_length=500,
    )
    thumbnail = models.ImageField(
        _('thumbnail'),
        upload_to=asset_upload,
        storage=S3Boto3Storage(bucket_name='clutchpoints-videos'),
        blank=True,
        null=True,
        max_length=500,
    )
    creator = models.ForeignKey(
        User,
        verbose_name=_('creator'),
        related_name='creator_video',
        on_delete=models.CASCADE,
        blank=True
    )
    status = models.CharField(
        _('status'),
        choices=STATUS_CHOICES,
        default=PROGRESS,
        max_length=255,
    )
    duration = models.IntegerField(_('duration'), blank=True, null=True)
    closed_captions = models.CharField(
        _('closed_captions'),
        max_length=255,
        blank=True,
        null=True,
    )
    categories = models.ManyToManyField(
        Category,
        verbose_name='categories',
        related_name='video',
        blank=True,
    )

    class Meta:
        ordering = ('title',)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)

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


class Playlist(BaseModel):
    title = models.CharField(_('title'), max_length=255)
    description = models.TextField(_('description'), blank=True, null=True)
    videos = models.ManyToManyField(Video, related_name='playlist')

    class Meta:
        ordering = ('title',)

    def __str__(self):
        return self.title