"""Keeps track of karma counts.
@package ppbot

@syntax .karma <item>
"""
import re

from modules import *

class Karmamod(Module):

    def __init__(self, *args, **kwargs):
        """Constructor"""

        Module.__init__(self, kwargs=kwargs)

    def _register_events(self):
        self.add_command('karma', 'get_karma')
        self.add_event('pubmsg', 'parsekarma')

    @op
    def get_karma(self, event):
        karma = self.db.karma.find_one({'name': event['args'][0].lower(),
            'source': event['target']})
        try:
            result = karma['count']
        except KeyError:
            result = 0

        self.msg(event['target'], '%s has %d karma.' % (event['args'][0], result))

    def parsekarma(self, event):
        inc_pattern = re.compile('([^ ]{2,})\+\+')
        m = inc_pattern.findall(event['message'])
        for term in m:
            self.change(event, term, 1)
        dec_pattern = re.compile('([^ ]{2,})--')
        m = dec_pattern.findall(event['message'])
        for term in m:
            self.change(event, term, -1)

    def change(self, event, name, value):
        """Change karma count."""

        karma = self.db.karma.find_one({'name': name.lower(),
            'source': event['target']})
        # TODO: find way to insert if doesn't exist or else update?
        try:
            count = karma['count'] + value
            self.db.karma.update({'name': name.lower(),
                'source': event['target']},
                {'count': count})
        except TypeError, KeyError:
            count = value
            self.db.karma.insert({'name': name.lower(),
                'source': event['target'],
                'count': count})

@@ -585,32 +585,43 @@
  except KeyError
+, TypeError
 :%0A            re
@@ -1412,16 +1412,21 @@
 update(%7B
+%0A%09%09%09%09
 'name': 
@@ -1484,28 +1484,36 @@
 et'%5D
-%7D,%0A                %7B
+%0A%09%09%09%7D, %7B%0A%09%09%09%09'$set': %7B%0A%09%09%09%09%09
 'cou
@@ -1522,16 +1522,26 @@
 ': count
+%0A%09%09%09%09%7D%0A%09%09%09
 %7D)%0A     

Fix karma mod update rewriting the row