from billy import db
from billy.commands import BaseCommand
from billy.utils import metadata
from billy.importers.names import NameMatcher
from billy.conf import settings


class UpdateLegIds(BaseCommand):
    name = 'update_leg_ids'
    help = '''update leg_ids for a specific session'''

    def add_args(self):
        self.add_argument('abbr', help='abbr to run matching for')
        self.add_argument('term', help='term to run matching for')

    def handle(self, args):
        nm = NameMatcher(args.abbr, args.term)

        for t in metadata(args.abbr)['terms']:
            if t['name'] == args.term:
                sessions = t['sessions']
                break
        else:
            print 'No such term for %s: %s' % (args.abbr, args.term)
            return

        for session in sessions:
            bills = db.bills.find({settings.LEVEL_FIELD: args.abbr,
                                   'session': session})

            for bill in bills:
                for sponsor in bill['sponsors']:
                    sponsor['leg_id'] = nm.match(sponsor['name'],
                                                 bill['chamber'])
                db.bills.save(bill, safe=True)

            votes = db.votes.find({settings.LEVEL_FIELD: args.abbr,
                                   'session': session})
            for vote in votes:
                for type in ('yes_votes', 'no_votes', 'other_votes'):
                    for voter in vote[type]:
                        voter['leg_id'] = nm.match(voter['name'],
                                                   vote['chamber'])
                db.votes.save(vote, safe=True)

@@ -1343,16 +1343,53 @@
  votes:%0A
+                vote%5B'_voters'%5D = %5B%5D%0A
         
@@ -1621,32 +1621,144 @@
 ote%5B'chamber'%5D)%0A
+                        if voter%5B'leg_id'%5D:%0A                            vote%5B'_voters'%5D.append(voter%5B'leg_id'%5D)%0A
                 

update _voters on update_leg_ids