from __future__ import unicode_literals

from django.db import models
from django.template.defaultfilters import slugify

from bible.models import BibleBook
from useraccounts.models import UserAccount


class Author(models.Model):
    name = models.CharField(null=False, blank=False, max_length=50)
    name_slug = models.SlugField(max_length=50, null=True, blank=True, db_index=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.name_slug is None or self.name_slug == "":
            self.name_slug = slugify(self.name)
        super(Author, self).save(*args, **kwargs)


class AuthorSetting(models.Model):
    """
    Holds user settings specific to an author.
    """

    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    user = models.ForeignKey("useraccounts.UserAccount", on_delete=models.CASCADE)
    name = models.CharField(max_length=30, db_index=True)
    value = models.CharField(max_length=50)


class Series(models.Model):
    name = models.CharField(null=False, blank=False, max_length=100)
    name_slug = models.SlugField(max_length=100, null=True, blank=True, db_index=True)
    author = models.ForeignKey(Author, null=False, blank=False, on_delete=models.CASCADE)
    complete = models.BooleanField(default=False)

    def __str__(self):
        return "%s (%s)" % (self.name, self.author.name)

    def save(self, *args, **kwargs):
        if self.name_slug is None or self.name_slug == "":
            self.name_slug = slugify(self.name)
        super(Series, self).save(*args, **kwargs)


class Sermon(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    date_preached = models.DateField(null=True, blank=True)
    author = models.ForeignKey(Author, related_name="sermons", on_delete=models.CASCADE)
    title = models.CharField(null=False, blank=False, max_length=100)
    title_slug = models.SlugField(max_length=100, null=True, blank=True, db_index=True)
    series = models.ForeignKey(
        Series, null=True, blank=True, related_name="sermons", on_delete=models.CASCADE
    )
    ref = models.CharField(max_length=20, null=True, blank=True)

    def get_audio_file(self):
        files = self.media_files.filter(media_type=1)
        return files[0] if len(files) > 0 else None

    def __str__(self):
        return "%s (by %s)" % (self.title, self.author.name)

    def save(self, *args, **kwargs):
        if self.title_slug is None or self.title_slug == "":
            self.title_slug = slugify(self.title)
        super(Sermon, self).save(*args, **kwargs)

    class Meta:
        ordering = ["-date_preached"]


class ScriptureRef(models.Model):
    sermon = models.ForeignKey(Sermon, related_name="scripture_refs", on_delete=models.CASCADE)
    bible_book = models.ForeignKey(BibleBook, on_delete=models.CASCADE)
    chapter_begin = models.PositiveSmallIntegerField()
    chapter_end = models.PositiveSmallIntegerField()
    verse_begin = models.PositiveSmallIntegerField(null=True, blank=True)
    verse_end = models.PositiveSmallIntegerField(null=True, blank=True)

    def __str__(self):
        end_string = ""
        if self.chapter_begin == self.chapter_end:
            end_string += "%s %s" % (self.bible_book.name, self.chapter_begin)
            if self.verse_begin is not None and self.verse_end is not None:
                if self.verse_begin == self.verse_end:
                    end_string += ":%s" % (self.verse_begin)
                else:
                    end_string += ":%s-%s" % (self.verse_begin, self.verse_end)
        else:
            end_string += "%s %s" % (self.bible_book.name, self.chapter_begin)
            if self.verse_begin is None and self.verse_end is None:
                end_string += "-%s" % (self.chapter_end)
            else:
                end_string += ":%s-%s:%s" % (self.verse_begin, self.chapter_end, self.verse_end)
        return end_string


class MediaFile(models.Model):
    MEDIA_TYPE_CHOICES = ((1, "audio"), (2, "video"), (3, "text"), (4, "pdf"))

    LOCATION_TYPE_CHOICES = ((1, "url"),)

    sermon = models.ForeignKey(Sermon, related_name="media_files", on_delete=models.CASCADE)
    media_type = models.PositiveSmallIntegerField(choices=MEDIA_TYPE_CHOICES, null=False, default=1)
    file_size = models.PositiveIntegerField(null=True, blank=True)
    location_type = models.PositiveSmallIntegerField(
        choices=LOCATION_TYPE_CHOICES, null=False, default=1
    )
    location = models.CharField(null=False, max_length=250)

    def __str__(self):
        return "%s (%s)" % (self.location, self.sermon.title)


class SermonSession(models.Model):
    sermon = models.ForeignKey(Sermon, related_name="sessions", on_delete=models.CASCADE)
    session_started = models.DateTimeField(auto_now_add=True)
    session_updated = models.DateTimeField(auto_now=True)
    position = models.PositiveSmallIntegerField(default=0)  # in seconds from start of file
    total_duration = models.PositiveSmallIntegerField(default=0)  # in seconds
    user = models.ForeignKey(UserAccount, on_delete=models.CASCADE)
    completed = models.BooleanField(default=False)
