# Path: gitcms/books/models.py
# class Book(models.Model):
#     slug = models.SlugField(u'slug')
#     title = models.CharField(u'title', max_length=255)
#     booktitle = models.CharField(u'title', max_length=255)
#     author = models.CharField(u'author', max_length=255)
#     tags = models.ManyToManyField(Tag)
#     content = models.TextField(u'content')
#     review_date = models.DateField(u'ReviewDate')
# 
#     def __unicode__(self):
#         return '<book review: %s>' % self.title
#     class Meta:
#         verbose_name_plural = tr(u'Books')
# 
# Path: gitcms/parsedate/parsedate.py
# def parsedate(daterep):
#     '''
#     time = parsedate(daterep)
#  
#     Parses a date written out in English.
#     '''
#     return _tryformats(daterep,
#             ['%d %b %Y', '%d %B %Y', '%b %d %Y', '%B %d %Y'],
#             "Cannot parse '%s' as a date" % daterep)
# 
# Path: gitcms/pages/load.py
# def loaddir(directory, clear=False):
#         A = Article(title=header['title'], url=url, meta=header.get('meta', ''), author=header.get('author', ''), content=content)
# 
# Path: gitcms/tagging/models.py
# def tag_for(slug):
#     '''
#     tag = tag_for(slug)
# 
#     Returns the Tag object corresponding to slug
# 
#     Raises an exception if not found.
#     '''
#     tags = Tag.objects.filter(slug=slug).all()
#     if len(tags) == 1:
#         return tags[0]
#     if not tags:
#         raise ValueError("gitcms.tagging.tag_for: No tag for slug '%s'" % slug)
#     raise ValueError("gitcms.tagging.tag_for: Multiple tags for slug '%s' (%s)" % (slug, [t.name for t in tags]))


from .models import Book
from os import path
from gitcms.parsedate import parsedate
from gitcms.pages.load import preprocess_rst_content
from gitcms.tagging.models import tag_for
import os
import yaml
import time


def loaddir(directory, clear=False):
    if clear:
        Book.objects.all().delete()

    queue = os.listdir(directory)
    while queue:
        next = queue.pop()
        if next[0] == '.': continue
        if next in ('categories', 'template'): continue
        next = path.join(directory, next)
        if path.isdir(next):
            queue.extend([
                path.join(next,f) for f in os.listdir(next)
                ])
            continue

        filecontent = file(next).read()
        header, content = filecontent.split('\n---\n')
        header = yaml.load(header)
        content = preprocess_rst_content(content)
        review_date = parsedate(header['review_date'])
        review_date = time.strftime('%Y-%m-%d', review_date)
        btags = []
        for c in header.get('tags','').split():
            btags.append(tag_for(c))

# Path: gitcms/books/models.py
# class Book(models.Model):
#     slug = models.SlugField(u'slug')
#     title = models.CharField(u'title', max_length=255)
#     booktitle = models.CharField(u'title', max_length=255)
#     author = models.CharField(u'author', max_length=255)
#     tags = models.ManyToManyField(Tag)
#     content = models.TextField(u'content')
#     review_date = models.DateField(u'ReviewDate')
# 
#     def __unicode__(self):
#         return '<book review: %s>' % self.title
#     class Meta:
#         verbose_name_plural = tr(u'Books')
# 
# Path: gitcms/parsedate/parsedate.py
# def parsedate(daterep):
#     '''
#     time = parsedate(daterep)
#  
#     Parses a date written out in English.
#     '''
#     return _tryformats(daterep,
#             ['%d %b %Y', '%d %B %Y', '%b %d %Y', '%B %d %Y'],
#             "Cannot parse '%s' as a date" % daterep)
# 
# Path: gitcms/pages/load.py
# def loaddir(directory, clear=False):
#         A = Article(title=header['title'], url=url, meta=header.get('meta', ''), author=header.get('author', ''), content=content)
# 
# Path: gitcms/tagging/models.py
# def tag_for(slug):
#     '''
#     tag = tag_for(slug)
# 
#     Returns the Tag object corresponding to slug
# 
#     Raises an exception if not found.
#     '''
#     tags = Tag.objects.filter(slug=slug).all()
#     if len(tags) == 1:
#         return tags[0]
#     if not tags:
#         raise ValueError("gitcms.tagging.tag_for: No tag for slug '%s'" % slug)
#     raise ValueError("gitcms.tagging.tag_for: Multiple tags for slug '%s' (%s)" % (slug, [t.name for t in tags]))


# Path: gitcms/books/load.py
from .models import Book
from os import path
from gitcms.parsedate import parsedate
from gitcms.pages.load import preprocess_rst_content
from gitcms.tagging.models import tag_for
import os
import yaml
import time



def loaddir(directory, clear=False):
    if clear:
        Book.objects.all().delete()

    queue = os.listdir(directory)
    while queue:
        next = queue.pop()
        if next[0] == '.': continue
        if next in ('categories', 'template'): continue
        next = path.join(directory, next)
        if path.isdir(next):
            queue.extend([
                path.join(next,f) for f in os.listdir(next)
                ])
            continue

        filecontent = file(next).read()
        header, content = filecontent.split('\n---\n')
        header = yaml.load(header)
        content = preprocess_rst_content(content)
        review_date = parsedate(header['review_date'])
        review_date = time.strftime('%Y-%m-%d', review_date)
        btags = []
        for c in header.get('tags','').split():
            btags.append(tag_for(c))

        B = Book(slug=header['slug'], title=header['title'], booktitle=header['booktitle'], author=header['author'], content=content, review_date=review_date)