#!/usr/bin/python3

import os
import sqlite3
import threading
import time
import urllib.request

import bottle
from bottle.ext import sqlite

DB = '/tmp/test.db'
PORT = '8085'
VEHICLE_ID = 1201


def create_db():
    # Vehicle Identity Card database
    print('Creating %s' % DB, flush=True)

    if os.path.exists(DB):
        os.unlink(DB)

    con = sqlite3.connect(DB)
    cur = con.cursor()
    cur.execute("CREATE TABLE vic(id, model, specification)")
    data = [
        (1000, 'Solaris', 'midibus'),
        (1200, 'eCitaro', 'standard'),
        (1500, 'Solaris', 'articulated'),
        (2100, 'Volvo7900', 'standard'),
    ]
    cur.executemany("INSERT INTO vic VALUES(?, ?, ?)", data)
    con.commit()
    con.close()

create_db()

app = bottle.Bottle()
plugin = sqlite.Plugin(dbfile=DB)
app.install(plugin)

@app.route('/vic/:item')
def vic(item, db):
    try:
        vehicle_id = int(item) // 100 * 100
        print('Retriving model %s' % vehicle_id, flush=True)
        row = db.execute('SELECT * from vic where id=%s' % vehicle_id).fetchone()
        return '<vic><model>%s</model><spec>%s</spec></vic>' % (row[1], row[2])
    except Exception as e:
        print(e, flush=True)
        os._exit(1)


server = threading.Thread(target=app.run, daemon=True, kwargs={'host':'0.0.0.0', 'port':PORT})
server.start()

print('Sleep 3 seconds', flush=True)
time.sleep(3)

with urllib.request.urlopen('http://localhost:%s/vic/%s' % (PORT, VEHICLE_ID)) as response:
   html = response.read()
   print('Got response code %s' % response.getcode(), flush=True)
   print(html.decode('ascii', 'ignore'), flush=True)
   assert response.getcode() == 200
   assert html == b'<vic><model>eCitaro</model><spec>standard</spec></vic>'

os._exit(0)
