#!/usr/bin/env python

import datetime
import re
import sqlite3
import subprocess

db = "words.sqlite3"
files = [
    'introduction.tex',
    'state.tex',
    'requirements.tex',
    'concept.tex',
    'implementation.tex',
    'validation.tex',
    'outlook.tex',
    'conclusion.tex',
    ]
reg = re.compile(r'(^\s+[0-9]+\+[0-9]+\+[0-9]+)(.*)(\s[a-z]+\.tex$)')

def get_wordcounts():
    command = ['texcount', '-utf8', '-total']
    command.extend(files)
    lines = subprocess.check_output(command).decode('utf8').split('\n')
    counts = {}
    for l in lines:
        m = reg.match(l)
        if m:
            count = int(m.groups()[0].strip().split('+')[0])
            tex = m.groups()[2].strip().split('.')[0]
            counts.update({tex: count})
        if l.startswith('Words in text'):
            counts.update({'total': int(l.split()[-1])})
    return counts

def log_wordcounts(con, counts):
    filecols = ",".join(["{} int".format(f.split(".")[0]) for f in files])
    countcols = ",".join([str(counts[f.split(".")[0]]) for f in files])
    with con:
        con.execute("create table if not exists Words (date datetime, {})".format(filecols))
        con.execute("insert into Words values (datetime(), {})".format(countcols))

if __name__ == '__main__':
    counts = get_wordcounts()
    dt = datetime.datetime.now()
    print("Current word counts on {}\n".format(datetime.datetime.strftime(dt, "%d %b %Y %H:%M")))
    for f in files:
        print("{}: {}".format(f.capitalize(), counts[f.split(".")[0]]))
    print("\nTotal: {}".format(counts["total"]))
    con = sqlite3.connect(db)
    log_wordcounts(con, counts)
    cur = con.execute("select * from Words where strftime('%Y-%m-%d', date) = strftime('%Y-%m-%d','now') order by date desc limit 1;")
    count_today = cur.fetchone()
    cur = con.execute("select * from Words where strftime('%Y-%m-%d', date) = strftime('%Y-%m-%d', date('now','-1 day')) order by date desc limit 1;")
    count_yesterday = cur.fetchone()
    if count_today and count_yesterday:
        total = sum(count_today[1:]) - sum(count_yesterday[1:])
        action = "added" if total > 0 else "deleted"
        print("\nTotal words {} since yesterday: {}\n".format(action, total))
    con.close()
    subprocess.call(["git", "add", db])
