#!/usr/bin/python

import mitsfs

d=mitsfs.dexdb()

((inventory_code, inventory_id, inventory_desc),) = \
    d.cursor.execute('select inventory_code, inventory_id, inventory_desc'
                     ' from inventory order by inventory_stamp desc limit 1')

print '%s (%s)' % (inventory_desc, inventory_code)

while True:
    packet = mitsfs.read('What packet are we working on? ').strip()
    if not packet:
        break
    try:
        (inventory_packet_id,) = d.cursor.execute('select inventory_packet_id from inventory_packet'
                                                  ' where inventory_packet_name=%s and inventory_id=%s', (packet, inventory_id))
    except ValueError:
        print "I don't see anything about a packet named",packet,'here.'
        continue

    entries = list(d.cursor.execute('select title_id, shelfcode, inventory_entry_id from inventory_entry natural left join inventory_missing'
                                    ' where missing and inventory_id=%s and inventory_packet_id=%s order by entry_number',
                                    (inventory_id, inventory_packet_id)))
    i = 0
    while True:
        if i < 0:
            i = 0
        if i >= len(entries):
            break
        title_id, shelfcode, entry = entries[i]
        print 'How many',shelfcode+'s','for',mitsfs.title(d, title_id)
        count = mitsfs.read('? ').strip()
        if count == '-':
            i -= 1
            continue
        try:
            count = int(count)
        except ValueError:
            print count, "doesn't seem to be a number, somehow"
            continue
        d.cursor.execute('update inventory_missing set missing_count=%s where inventory_entry_id=%s',
                         (count, entry))
        d.db.commit()
        
        
        
            
