#!/usr/bin/python

import sys, mitsfs

d=mitsfs.dexdb(dsn=mitsfs.database_dsn)

if len(sys.argv) == 1:
    ((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')
else:
    _, inventory_code = sys.argv
    ((inventory_id, inventory_desc),) = \
        d.cursor.execute('select inventory_id, inventory_desc'
                         ' from inventory where inventory_code=%s',
                         (inventory_code,))

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

while True:
    shelfcode = mitsfs.read('Shelfcode (q to quit)? ', callback=mitsfs.codes.keys, history='shelfcode').upper().strip()

    if not shelfcode:
        continue
    if shelfcode.strip().lower() == 'q':
        break

    try:
        (shelfcode_id,) = d.cursor.execute('select shelfcode_id from shelfcode where shelfcode=%s', (shelfcode,))
    except ValueError:
        print 'Unknown shelfcode'
        continue

    print mitsfs.codes[shelfcode].name

    title = None
    while True:
        print
        title = mitsfs.specify(d, title)

        if not title:
            break

        print title

        try:
            mstr = mitsfs.read('How many missing? ', history='count').strip()
            if mstr=='':
                missing = 1
            else:
                missing = int(mstr)
        except ValueError:
            print '?'
            continue
        if missing >= 0:
            print title.title_id, missing, title
            ieds = d.cursor.execute('select inventory_entry_id from inventory_entry'
                                    ' where shelfcode_id=%s and inventory_id=%s and title_id=%s',
                                    (shelfcode_id, inventory_id, title.title_id))
            ieds = list(ieds)
            try:
                (inventory_entry_id,) = ieds
            except ValueError:
                if ieds:
                    print 'too many titles', ieds
                else:
                    print 'Title not found in shelf packet'
                continue
            d.cursor.execute('delete from inventory_missing where inventory_entry_id=%s', (inventory_entry_id,))
            d.cursor.execute('insert into inventory_missing(inventory_entry_id, missing_count)'
                             ' values (%s,%s)', (inventory_entry_id, missing))
            d.db.commit()
            title = None
            

    
