#!/usr/bin/python

from __future__ import division

import argparse

from digikey import robot
import digikey

parser = argparse.ArgumentParser()

parser.add_argument('inductance', metavar='INDUCTANCE', type=str, help='inductance (example: 2.2u)')
parser.add_argument('--tolerance', metavar='TOLERANCE', type=float, help='tolerance in percent (default: 1)', default=1)
parser.add_argument('--package', metavar='PACKAGE', type=str, help='package / case (default: 0603) (use ANY for any)', default='0603')

args = parser.parse_args()


r = robot.Robot.start('http://www.digikey.com/product-search/en/inductors-coils-chokes/fixed-inductors')
fp = digikey.FilteringPage(r)

#print r.html


options = []
options.append(('quantity', 10))
options.append(('stock', 1))
options.append(('ColumnSort', 1000011)) # XXX does this change?
options.extend(fp.produce_filter_options('Inductance',
    lambda s: digikey.parse_number(s) is not None and digikey.within_tolerance(digikey.parse_number(args.inductance), args.tolerance, digikey.parse_number(s))))
options.extend(fp.produce_filter_options('Package / Case',
    lambda s: s.strip().startswith(args.package) or args.package == 'ANY'))
print options

url = r.get_new_url(options=options)
print url

r2 = robot.Robot.start(url)
rp = digikey.FilteringPage(r2)
print rp.first_part_number
