from datetime import datetime

from bottle import abort, default_app, response, route, run
from rss2producer import RSS2Feed
import dataset

from settings import TABLE


# copy pasted from scraper
LIMIT = 50


@route('/')
def index():
    return 'TODO'


@route('/<slug>/')
def feed_detail(slug):
    db = dataset.connect()  # uses DATABASE_URL
    # table = db.load_table(TABLE)  # don't allow dataset to create the table
    feed = RSS2Feed(
        title='Boards and Commissions',
        link='http://www.austintexas.gov/cityclerk/boards_commissions/',
        description='Feed of Boards and Commissions',
    )
    filter_kwargs = {}
    if slug != 'all':
        filter_kwargs['bandc'] = slug
    # results = table.find(_limit=LIMIT, order_by='-date', **filter_kwargs)
    # HACK for 'order_by' not working
    sql = 'SELECT * from {} ORDER BY date DESC LIMIT {}'.format(
        TABLE,
        LIMIT,
    )
    results = db.query(sql)
    import re
    for row in results:
        title = row['title'] or row['type']
        if slug == 'all':
            title = '[{}] {}'.format(row['bandc'], title)
        text = row['text'].strip().encode('ascii', 'ignore')[:600].strip()
        text = re.sub(r'\s+', ' ', text)[:500]
        if text:
            print text
        feed.append_item(
            title=title,
            link=row['url'],
            # description=row['type'],
            # description=row['text'].decode('utf8').strip()[:100],  # TODO truncate words
            # description=row['text'].strip()[:100],  # TODO truncate words
            description=text if text and not text.startswith('no text') else row['type'],
            # convert date into datetime
            pub_date=datetime.combine(row['date'], datetime.min.time()),
        )
    # TODO if no results, abort(404, 'No results for that BandC')
    response.content_type = 'application/rss+xml'
    return feed.get_xml()


app = default_app()


if __name__ == '__main__':
    run(host='localhost', port=8000, reloader=True)

@@ -160,16 +160,23 @@
 rt TABLE
+, PAGES
 %0A%0A%0A# cop
@@ -214,94 +214,389 @@
 0%0A%0A%0A
-@route('/')%0Adef index():%0A    return 'TODO'%0A%0A%0A@route('/%3Cslug%3E/')%0Adef feed_detail(slug):
+slug_to_name = %7Bslug: name for slug, pk, name in PAGES%7D%0A%0A%0A@route('/')%0Adef index():%0A    out = %5B%5D%0A    for slug, pk, name in PAGES:%0A        out.append('%3Cli%3E%3Ca href=%22%7B%7D/%22%3E%7B%7D%3C/a%3E%3C/li%3E'.format(slug, name))%0A    return u''.join(out)%0A%0A%0A@route('/%3Cslug%3E/')%0Adef feed_detail(slug):%0A    if slug != 'all' and slug not in slug_to_name:%0A        abort(404, 'No results for that Board or Commission')
 %0A   
@@ -2070,74 +2070,8 @@
   )%0A
-    # TODO if no results, abort(404, 'No results for that BandC')%0A
     

add an index page to the feed