#!/usr/bin/env python3
import bottle
import sqlite3


application = bottle.default_app()
connection = sqlite3.connect("db.sqlite")
cursor = connection.cursor()
cursor.execute("""
    CREATE TABLE IF NOT EXISTS visitors (
        id      INTEGER PRIMARY KEY AUTOINCREMENT,
        event   TEXT,
        time    DATETIME,
        name    TEXT,
        address TEXT,
        contact TEXT
    );
    """)


@application.get("/")
@bottle.view("template/new.tpl")
def new_get():
    pass


@application.post("/")
@bottle.view("template/new.tpl")
def new_post():
    event = bottle.request.forms.get("event", "")
    if event:
        bottle.redirect("event/" + event)
    return dict(event=event, feedback=True)


@application.get("/static/<file:path>")
def static_get(file):
    return bottle.static_file(file, root="static")


@application.get("/event/<event>")
@bottle.view("template/event.tpl")
def event_get(event):
    return dict(event=event)


@application.post("/event/<event>")
@bottle.view("template/event.tpl")
def event_post(event):
    data = dict(feedback=True, success=True)
    for field in ("event", "name", "address", "contact"):
        data[field] = bottle.request.forms.get(field, "")
        data["success"] = data["success"] and data[field]
    if data["success"]:
        cursor.execute("""
            INSERT INTO visitors (event, time, name, address, contact)
                VALUES (:event, datetime('now'), :name, :address, :contact);
            """, data)
        connection.commit()
    return data


@application.get("/cleanup")
def cleanup():
    cursor.execute("""
        DELETE FROM visitors WHERE time < datetime('now', '-1 month');
        """)
    connection.commit()


if __name__ == "__main__":
    bottle.run(host="0.0.0.0", port=8080)
else:
    application.catchall = False