#! /usr/bin/env python

import MySQLdb
import sys
import re
from datetime import datetime
import notify_send
import os.path

DBHOST = '10.1.1.203'
DBUSER = 'anonymous'
DBNAME = 'test'
LOGFILE = '~/scanner-text-%d.log'
notify_send.INADDR_BC = '<broadcast>'

print "host:",DBHOST,"user",DBUSER,"db",DBNAME
db = MySQLdb.connect(host=DBHOST, user=DBUSER, db=DBNAME)

cursor = db.cursor()
digits = re.compile('^\d+\n?$')
notifier = notify_send.Say()

sql = "insert into scans (bib, scantime) values (%s, '%s')"

def WriteLog(sql_command):
    fname = os.path.expanduser(LOGFILE % os.getpid())
    open(fname, 'a').write("%s;\n" % sql_command)

while True:
    line = sys.stdin.readline()
    if digits.match(line):
        formatted = sql % (line, datetime.now().isoformat())
        cursor.execute(formatted)
        WriteLog(formatted)
        print "Recorded"
        notifier.NotifyAll()
    else:
        print "Non-digit input ignored"


