#!/usr/bin/python

import mitsfs
from itertools import groupby

d=mitsfs.dexdb(dsn=mitsfs.database_dsn)
c=d.getcursor()
inventory=mitsfs.inventory(d, 'purge0802')

divs=dict((shelfcode, dict((title_id, box) for (shelfcode, title_id, box) in group))
          for (shelfcode, group)
          in groupby(c.execute('select shelfcode, title_id, division_comment'
                               ' from shelf_divisions natural join shelfcode'
                               ' where inventory_id=%s', (inventory.id,)),
                     lambda l: l[0]))


codemap = {'C/P': 'P', 'H': 'H', 'C/REF-P': 'REF-P', 'C/REF-H': 'REF-H'}

commit = False

for shelfcode in divs:
    shelfdivs = divs[shelfcode]
    box = None
    for title_id, expected, missing in \
        list(c.execute('select title_id, entry_expected, missing_count'
                  ' from inventory_entry natural join inventory_packet'
                  '  natural left join inventory_missing'
                  ' where inventory_packet_name=%s and inventory_id=%s'
                  ' order by entry_number',
                  (shelfcode, inventory.id))):
        newbox = False
        if title_id in shelfdivs:
            box = shelfdivs[title_id]
            boxcode = 'KBX/' + codemap[shelfcode] + box[3:] # XXX KLUUUUDGE
            newbox = True
        if None is missing:
            count = expected
        else:
            count = expected - missing
        if count == 0:
            continue
        if newbox:
            print
            print
        t=mitsfs.title(d, title_id)
        codes=mitsfs.shelfcodes({shelfcode: -count, boxcode: count})
        l=mitsfs.dexline(authors=t.authors, titles=t.titles, series=t.series, codes=codes)
        if commit:
            d.add(l)
        print codes, t
