#!/usr/bin/env python
# 
# Inspired by Aaron Schwartz's http://webpy.appspot.com/

__author__ = "Yoan Blanc <yoan at dosimple dot ch>"

import web

from datetime import datetime
from couchdb import client

urls = (
    '/', 'index',
    '/note', 'note',
    '/source', 'source',
)

render = web.template.render('templates/')

# set up
server = client.Server('http://localhost:5984/')
if 'webpy' in server:
    db = server['webpy']
else:
    db = server.create('webpy')
    
    db['_design/note'] = {
        'views': {
            'all': '''function(doc) {
                    if(doc.type === 'Note') {
                        map(doc.created, doc);
                    }
                }''',
        }
    }

class index:
    def GET(self):
        max = 10
        notes = db.view('_view/note/all', descending=True, count=max)

        return render.index(notes, min(notes.total_rows, max))

class note:
    def POST(self):
        i = web.input('content')
        db.create({'type': 'Note', 'content': i.content, 'created': str(datetime.now()) })
        return web.seeother('/')

class source:
    def GET(self):
        web.header('Content-Type', 'text/plain')
        return '\n\n'.join((
          '## code.py', 
          file('code.py').read(),
          '## templates/index.html',
          file('templates/index.html').read()
        ))

app = web.application(urls, globals())
app.run()
