# Path: henet/util.py
# def parse_article(path, cache_dir, root_path):
#     if not os.path.exists(cache_dir):
#         os.makedirs(cache_dir)
# 
#     # XXX two reads...
#     with open(path) as f:
#         file_md5 = md5(f.read())
# 
#     cache = os.path.join(cache_dir, file_md5)
# 
#     if os.path.exists(cache):
#         with open(cache) as f:
#             article = Article(bson.loads(f.read()))
#     else:
#         article = parse(path)
#         article['filename'] = path[len(root_path):].lstrip('/')
#         with open(cache, 'w') as f:
#             f.write(bson.dumps(article))
# 
#     return article
# 
# Path: henet/article.py
# class Article(dict):
#     def __init__(self, *args, **kw):
#         dict.__init__(self, *args, **kw)
#         if 'metadata' not in self:
#             self['metadata'] = {}
#             self['metadata_source'] = ''
#         if 'title_source' not in self:
#             self['title_source'] = ''
#         if 'body' not in self:
#             self['body'] = ''
#         if 'original_source' not in self:
#             self['original_source'] = ''
#         self.warnings = []
# 
#     def set_metadata(self, key, value):
#         self['metadata'][key.lower()] = value
#         self._update_metadata_source()
# 
#     def _update_metadata_source(self):
#         def _convert(value):
#             if isinstance(value, datetime):
#                 return unicode(value.strftime('%Y-%m-%d %H:%M'))
#             if isinstance(value, str):
#                 return value.decode('utf8')
#             return value
# 
#         metadata = [u':%s: %s' % (name, _convert(value)) for name, value in
#                     self['metadata'].items()]
#         metadata = u'\n'.join(metadata)
#         self['metadata_source'] = metadata
# 
#     def __setitem__(self, key, val):
#         dict.__setitem__(self, key, val)
#         if key == 'title':
#             self['title_source'] = val + u'\n' + u'=' * len(val)
# 
#     def render(self):
#         res = self['title_source'] + u'\n\n'
#         res += self['metadata_source'] + u'\n\n'
#         res += self['body']
#         if not res.endswith(u'\n'):
#             res += u'\n'
#         return res.replace(u'\r\n', '\n')
# 
# Path: henet/events.py
# def emit(event, **data):
#     for subscriber in _SUBSCRIBERS[event]:
#         subscriber(event, **data)
#     for subscriber in _SUBSCRIBERS[ALL_EVENTS]:
#         subscriber(event, **data)
# 
# EVENT_CHANGED_CONTENT = 0
# 
# EVENT_CREATED_CONTENT = 2
# 
# EVENT_DELETED_CONTENT = 1


import os
import datetime
from bottle import route, request, app, post, redirect
from pelican.utils import slugify
from bottle_utils.csrf import csrf_protect, csrf_token
from bottle_utils.i18n import lazy_gettext as _
from henet.util import parse_article
from henet.article import Article
from henet.events import (emit, EVENT_CHANGED_CONTENT, EVENT_CREATED_CONTENT,
                          EVENT_DELETED_CONTENT)

    with open(article_path, 'w') as f:
        f.write(article.render().encode('utf8'))

    emit(EVENT_CHANGED_CONTENT, article_path=article_path)
    redirect('/page/%s/%s' % (page, article['filename']))


@post("/category/<category>/<article:path>", no_i18n=True)
@csrf_protect
def post_article(category, article):
    data = dict(request.POST.decode())
    cache_dir = app._config['henet']['cache_dir']
    cat_path = dict(app.vars['categories'])[category]['path']
    article_path = os.path.join(cat_path, article)
    article = parse_article(article_path, cache_dir, cat_path)

    # XXX all this update crap should be in a Document() class
    if 'title' in data:
        article['title'] = data['title']
    if 'content' in data:
        article['body'] = data['content']

    for meta in ('location', 'date', 'eventdate'):
        if meta in data:
            article.set_metadata(meta, data[meta])

    with open(article_path, 'w') as f:
        f.write(article.render().encode('utf8'))


# Path: henet/util.py
# def parse_article(path, cache_dir, root_path):
#     if not os.path.exists(cache_dir):
#         os.makedirs(cache_dir)
# 
#     # XXX two reads...
#     with open(path) as f:
#         file_md5 = md5(f.read())
# 
#     cache = os.path.join(cache_dir, file_md5)
# 
#     if os.path.exists(cache):
#         with open(cache) as f:
#             article = Article(bson.loads(f.read()))
#     else:
#         article = parse(path)
#         article['filename'] = path[len(root_path):].lstrip('/')
#         with open(cache, 'w') as f:
#             f.write(bson.dumps(article))
# 
#     return article
# 
# Path: henet/article.py
# class Article(dict):
#     def __init__(self, *args, **kw):
#         dict.__init__(self, *args, **kw)
#         if 'metadata' not in self:
#             self['metadata'] = {}
#             self['metadata_source'] = ''
#         if 'title_source' not in self:
#             self['title_source'] = ''
#         if 'body' not in self:
#             self['body'] = ''
#         if 'original_source' not in self:
#             self['original_source'] = ''
#         self.warnings = []
# 
#     def set_metadata(self, key, value):
#         self['metadata'][key.lower()] = value
#         self._update_metadata_source()
# 
#     def _update_metadata_source(self):
#         def _convert(value):
#             if isinstance(value, datetime):
#                 return unicode(value.strftime('%Y-%m-%d %H:%M'))
#             if isinstance(value, str):
#                 return value.decode('utf8')
#             return value
# 
#         metadata = [u':%s: %s' % (name, _convert(value)) for name, value in
#                     self['metadata'].items()]
#         metadata = u'\n'.join(metadata)
#         self['metadata_source'] = metadata
# 
#     def __setitem__(self, key, val):
#         dict.__setitem__(self, key, val)
#         if key == 'title':
#             self['title_source'] = val + u'\n' + u'=' * len(val)
# 
#     def render(self):
#         res = self['title_source'] + u'\n\n'
#         res += self['metadata_source'] + u'\n\n'
#         res += self['body']
#         if not res.endswith(u'\n'):
#             res += u'\n'
#         return res.replace(u'\r\n', '\n')
# 
# Path: henet/events.py
# def emit(event, **data):
#     for subscriber in _SUBSCRIBERS[event]:
#         subscriber(event, **data)
#     for subscriber in _SUBSCRIBERS[ALL_EVENTS]:
#         subscriber(event, **data)
# 
# EVENT_CHANGED_CONTENT = 0
# 
# EVENT_CREATED_CONTENT = 2
# 
# EVENT_DELETED_CONTENT = 1


# Path: henet/views/article.py
import os
import datetime
from bottle import route, request, app, post, redirect
from pelican.utils import slugify
from bottle_utils.csrf import csrf_protect, csrf_token
from bottle_utils.i18n import lazy_gettext as _
from henet.util import parse_article
from henet.article import Article
from henet.events import (emit, EVENT_CHANGED_CONTENT, EVENT_CREATED_CONTENT,
                          EVENT_DELETED_CONTENT)


    with open(article_path, 'w') as f:
        f.write(article.render().encode('utf8'))

    emit(EVENT_CHANGED_CONTENT, article_path=article_path)
    redirect('/page/%s/%s' % (page, article['filename']))


@post("/category/<category>/<article:path>", no_i18n=True)
@csrf_protect
def post_article(category, article):
    data = dict(request.POST.decode())
    cache_dir = app._config['henet']['cache_dir']
    cat_path = dict(app.vars['categories'])[category]['path']
    article_path = os.path.join(cat_path, article)
    article = parse_article(article_path, cache_dir, cat_path)

    # XXX all this update crap should be in a Document() class
    if 'title' in data:
        article['title'] = data['title']
    if 'content' in data:
        article['body'] = data['content']

    for meta in ('location', 'date', 'eventdate'):
        if meta in data:
            article.set_metadata(meta, data[meta])

    with open(article_path, 'w') as f:
        f.write(article.render().encode('utf8'))


    emit(EVENT_CHANGED_CONTENT, article_path=article_path)