# Path: books/models.py
# class Book(models.Model):
#     """
#     This model stores the book file, and all the metadata that is
#     needed to publish it in a OPDS atom feed.
# 
#     It also stores other information, like tags and downloads, so the
#     book can be listed in OPDS catalogs.
# 
#     """
#     book_file = models.FileField(upload_to='books')
#     file_sha256sum = models.CharField(max_length=64, unique=True)
#     mimetype = models.CharField(max_length=200, null=True)
#     time_added = models.DateTimeField(auto_now_add=True)
#     tags = TaggableManager(blank=True)
#     downloads = models.IntegerField(default=0)
#     a_id = UUIDField('atom:id')
#     a_status = models.ForeignKey(Status, blank=False, null=False, default=settings.DEFAULT_BOOK_STATUS)
#     a_title = models.CharField('atom:title', max_length=200)
#     a_author = models.ForeignKey(Author, blank=False, null=False)
#     a_updated = models.DateTimeField('atom:updated', auto_now=True)
#     a_summary = models.TextField('atom:summary', blank=True)
#     a_category = models.CharField('atom:category', max_length=200, blank=True)
#     a_rights = models.CharField('atom:rights', max_length=200, blank=True)
#     dc_language = models.ForeignKey(Language, blank=True, null=True)
#     dc_publisher = models.CharField('dc:publisher', max_length=200, blank=True)
#     dc_issued = models.CharField('dc:issued', max_length=100, blank=True)
#     dc_identifier = models.CharField('dc:identifier', max_length=50, \
#     help_text='Use ISBN for this', blank=True)
#     cover_img = models.FileField(blank=True, upload_to='covers')
# 
#     def validate_unique(self, *args, **kwargs):
#         if not self.file_sha256sum:
#             self.file_sha256sum = sha256_sum(self.book_file)
#         unicity = self.__class__.objects.filter(file_sha256sum=self.file_sha256sum)
#         if self.pk is not None:
#             unicity = unicity.exclude(pk=self.pk)
#         if unicity.exists():
#             raise ValidationError({
#                 NON_FIELD_ERRORS:['The book already exists in the server.',]})
# 
#     def save(self, *args, **kwargs):
#         assert self.file_sha256sum
#         if not self.cover_img:
#             # FIXME: we should use mimetype
#             if self.book_file.name.endswith('.epub'):
#                 # get the cover path from the epub file
#                 epub_file = Epub(self.book_file)
#                 cover_path = epub_file.get_cover_image_path()
#                 if cover_path is not None and os.path.exists(cover_path):
#                     cover_file = File(open(cover_path, "rb"))
#                     self.cover_img.save(os.path.basename(cover_path), # pylint: disable=no-member
#                                         cover_file)
#                 epub_file.close()
# 
#         super(Book, self).save(*args, **kwargs)
# 
#     class Meta:
#         ordering = ('-time_added',)
#         get_latest_by = "time_added"
# 
#     def __unicode__(self):
#         return self.a_title
# 
#     def __str__(self):
#         return self.a_title
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return ('book_detail', [self.pk])


from django.db.models import Q
from books.models import Book
    """
    Does an advanced search in several fields of the books.
    """
    q_objects = []
    results = queryset

    subterms = searchterms.split('AND')
    for subterm in subterms:
        if ':' in subterm:
            key, word = subterm.split(':')
            key = key.strip()
            if key == 'title':
                q_objects.append(Q(a_title__icontains = word))
            if key == 'author':
                q_objects.append(Q(a_author__icontains = word))
            if key == 'publisher':
                q_objects.append(Q(dc_publisher__icontains = word))
            if key == 'identifier':
                q_objects.append(Q(dc_identifier__icontains = word))
            if key == 'summary':
                q_objects.append(Q(a_summary__icontains = word))
        else:
            word = subterm
            try:
                results = results.filter(Q(a_title__icontains = word) | \
                    Q(a_author__a_author__icontains = word) | \
                    Q(dc_publisher__icontains = word) | \
                    Q(dc_identifier__icontains = word) | \
                    Q(a_summary__icontains = word))
            except Book.DoesNotExist:

# Path: books/models.py
# class Book(models.Model):
#     """
#     This model stores the book file, and all the metadata that is
#     needed to publish it in a OPDS atom feed.
# 
#     It also stores other information, like tags and downloads, so the
#     book can be listed in OPDS catalogs.
# 
#     """
#     book_file = models.FileField(upload_to='books')
#     file_sha256sum = models.CharField(max_length=64, unique=True)
#     mimetype = models.CharField(max_length=200, null=True)
#     time_added = models.DateTimeField(auto_now_add=True)
#     tags = TaggableManager(blank=True)
#     downloads = models.IntegerField(default=0)
#     a_id = UUIDField('atom:id')
#     a_status = models.ForeignKey(Status, blank=False, null=False, default=settings.DEFAULT_BOOK_STATUS)
#     a_title = models.CharField('atom:title', max_length=200)
#     a_author = models.ForeignKey(Author, blank=False, null=False)
#     a_updated = models.DateTimeField('atom:updated', auto_now=True)
#     a_summary = models.TextField('atom:summary', blank=True)
#     a_category = models.CharField('atom:category', max_length=200, blank=True)
#     a_rights = models.CharField('atom:rights', max_length=200, blank=True)
#     dc_language = models.ForeignKey(Language, blank=True, null=True)
#     dc_publisher = models.CharField('dc:publisher', max_length=200, blank=True)
#     dc_issued = models.CharField('dc:issued', max_length=100, blank=True)
#     dc_identifier = models.CharField('dc:identifier', max_length=50, \
#     help_text='Use ISBN for this', blank=True)
#     cover_img = models.FileField(blank=True, upload_to='covers')
# 
#     def validate_unique(self, *args, **kwargs):
#         if not self.file_sha256sum:
#             self.file_sha256sum = sha256_sum(self.book_file)
#         unicity = self.__class__.objects.filter(file_sha256sum=self.file_sha256sum)
#         if self.pk is not None:
#             unicity = unicity.exclude(pk=self.pk)
#         if unicity.exists():
#             raise ValidationError({
#                 NON_FIELD_ERRORS:['The book already exists in the server.',]})
# 
#     def save(self, *args, **kwargs):
#         assert self.file_sha256sum
#         if not self.cover_img:
#             # FIXME: we should use mimetype
#             if self.book_file.name.endswith('.epub'):
#                 # get the cover path from the epub file
#                 epub_file = Epub(self.book_file)
#                 cover_path = epub_file.get_cover_image_path()
#                 if cover_path is not None and os.path.exists(cover_path):
#                     cover_file = File(open(cover_path, "rb"))
#                     self.cover_img.save(os.path.basename(cover_path), # pylint: disable=no-member
#                                         cover_file)
#                 epub_file.close()
# 
#         super(Book, self).save(*args, **kwargs)
# 
#     class Meta:
#         ordering = ('-time_added',)
#         get_latest_by = "time_added"
# 
#     def __unicode__(self):
#         return self.a_title
# 
#     def __str__(self):
#         return self.a_title
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return ('book_detail', [self.pk])


# Path: books/search.py
from django.db.models import Q
from books.models import Book

    """
    Does an advanced search in several fields of the books.
    """
    q_objects = []
    results = queryset

    subterms = searchterms.split('AND')
    for subterm in subterms:
        if ':' in subterm:
            key, word = subterm.split(':')
            key = key.strip()
            if key == 'title':
                q_objects.append(Q(a_title__icontains = word))
            if key == 'author':
                q_objects.append(Q(a_author__icontains = word))
            if key == 'publisher':
                q_objects.append(Q(dc_publisher__icontains = word))
            if key == 'identifier':
                q_objects.append(Q(dc_identifier__icontains = word))
            if key == 'summary':
                q_objects.append(Q(a_summary__icontains = word))
        else:
            word = subterm
            try:
                results = results.filter(Q(a_title__icontains = word) | \
                    Q(a_author__a_author__icontains = word) | \
                    Q(dc_publisher__icontains = word) | \
                    Q(dc_identifier__icontains = word) | \
                    Q(a_summary__icontains = word))
            except Book.DoesNotExist:

                results = Book.objects.none()