
from django.conf import settings
from django.db import models


class Gender(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)

    class Meta:
        unique_together = ['name']
        ordering = ['name']
        verbose_name = 'Género'
        verbose_name_plural = 'Generos'

    def __str__(self):
        return self.name


class Country(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250, verbose_name='País')

    class Meta:
        unique_together = ['name']
        ordering = ['name']
        verbose_name = 'País'
        verbose_name_plural = 'Paises'

    def __str__(self):
        return self.name


class PersonQuerySet(models.QuerySet):

    def directors(self):
        rows = self.filter(is_director=True).values_list('name', flat=True)
        return rows

    def actors(self):
        rows = self.filter(is_actor=True).values_list('name', flat=True)
        return rows


class Person(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField('Nombre',
        max_length=500)
    country = models.ForeignKey(Country,
        related_name='country', on_delete=models.PROTECT)
    date_born = models.DateField('Fecha de nacimiento',
        null=True, blank=True)
    is_actor = models.BooleanField('Es Actor',
        default=False)
    is_director = models.BooleanField('Es Director',
        default=False)
    is_woman = models.BooleanField('Es mujer',
        default=False)
    photo = models.ImageField('Fotografía', upload_to='%Y/%m/%d/',
        null=True, blank=True)
    objects = PersonQuerySet.as_manager()

    class Meta:
        unique_together = ['name']
        ordering = ['name']
        verbose_name = 'Persona'
        verbose_name_plural = 'Personas'

    def __str__(self):
        return self.name


class MovieQuerySet(models.QuerySet):

    def _to_str(self, q):
        return ','.join([r.name for r in q.all()])

    def _to_link(self, file_name):
        # ~ folder = file_name[0].upper()
        # ~ if folder.isdigit():
            # ~ folder = '0'
        url = settings.URL_CDN.format(file_name)
        return url

    def _to_image(self, img, director=''):
        data = ''
        if img:
            url = '../'
            if director:
                url = '../../'
            data = url + img.url
        return data

    def to_dict(self, query='', director='', id=0):
        rows = self.all().order_by('-id')[:10]
        if query == 'all':
            rows = self.all()
        elif id:
            rows = self.filter(id=id)
            director = ' '
        else:
            if director:
                rows = self.filter(directors__name__iexact=director)
            elif query:
                rows = self.filter(name__icontains=query)

        movies = []
        for row in rows:
            data = {}
            data['id'] = row.id
            data['url'] = self._to_link(row.file_name)
            data['name'] = row.name
            data['year'] = row.year
            data['original_name'] = row.original_name
            data['duration'] = row.duration
            data['director'] = self._to_str(row.directors)
            data['country'] = self._to_str(row.countries)
            data['count'] = row.count
            data['image'] = self._to_image(row.cartel, director)
            movies.append(data)

        matrix = []
        for i in range (0, len(movies), 4):
            matrix.append(movies[i:i+4])
        return matrix

    def get_directors(self):
        data = self.distinct().values_list(
            'directors__name', flat=True).order_by('directors')
        return data


def upload_cartel(instance, filename):
    first = filename[0].upper()
    if first.isdigit():
        first = '0'
    return f'{first}/{filename}'


class Movie(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField('Nombre',
        max_length=1000)
    original_name = models.CharField('Nombre original',
        max_length=1000, default='', blank=True)
    file_name = models.CharField('Nombre archivo',
        max_length=1000, default='', blank=True)
    year = models.PositiveSmallIntegerField('Año',
        default=1900)
    duration = models.PositiveSmallIntegerField('Duración',
        default=0)
    directors = models.ManyToManyField(Person, verbose_name='Director',
        related_name='directors')
    actors = models.ManyToManyField(Person,
        related_name='actors', blank=True)
    countries = models.ManyToManyField(Country,
        related_name='countries', verbose_name='País', blank=True)
    genders = models.ManyToManyField(Gender,
        related_name='genders', verbose_name='Género', blank=True)
    cartel = models.ImageField('Cartel', upload_to=upload_cartel,
        null=True, blank=True)
    count = models.PositiveIntegerField('Descargas',
        default=0)
    stars = models.PositiveSmallIntegerField('Estrellas',
        default=0)
    published = models.BooleanField('¿Publicar?',
        default=True)
    is_digital = models.BooleanField('Es digital',
        default=False)
    objects = MovieQuerySet.as_manager()

    class Meta:
        unique_together = ['name', 'original_name']
        ordering = ['name']
        verbose_name = 'Película'
        verbose_name_plural = 'Películas'

    def __str__(self):
        return self.name

