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

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

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

from modules import *
from models import Model

Base = declarative_base()


class Karma(Base, Model):
    __tablename__ = 'karma_karmas'

    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    source = Column(String(50), nullable=False)
    count = Column(Integer, nullable=False)

    def __init__(self, **kwargs):
        Model.__init__(self)
        Base.__init__(self)
        self.metadata = Base.metadata

        for name, val in kwargs.iteritems():
            self.__setattr__(name, val)

    def __repr__(self):
        return "<Karma: %s=%s>" % (self.name, self.count)

    def get(self, **kwargs):
        return self.session.query(Karma).filter_by(
                name=self.name, source=self.source
                )

    def change_karma(self, val, **kwargs):
        if self.get().count() > 0:
            self.get().update({Karma.count: Karma.count + self.count})
            self.session.commit()
        else:
            self.save()


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')

    def get_karma(self, event):
        karma = Karma(name=event['args'][0], source=event['target'])
        result = karma.get().first()
        self.msg(event['target'], '%s has %d karma.' % (event['args'][0], result.count))

    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 = Karma(name=name, source=event['target'], count=value)
        karma.change_karma(value)

@@ -180,16 +180,61 @@
 ive_base
+%0Afrom sqlalchemy.orm.exc import NoResultFound
 %0A%0Afrom m
@@ -437,10 +437,10 @@
 ing(
-10
+25
 0), 
@@ -1033,32 +1033,49 @@
 val, **kwargs):%0A
+        try:%0A    
         if self.
@@ -1101,24 +1101,28 @@
             
+    
 self.get().u
@@ -1176,24 +1176,28 @@
             
+    
 self.session
@@ -1218,14 +1218,22 @@
     
+    
 else:%0A
+    
     
@@ -1248,24 +1248,57 @@
 self.save()%0A
+        except:%0A            pass%0A
 %0A%0Aclass Karm
@@ -1650,24 +1650,41 @@
 %5B'target'%5D)%0A
+        try:%0A    
         resu
@@ -1704,15 +1704,73 @@
 t().
-first()
+one().count%0A        except NoResultFound:%0A            result = 0%0A
 %0A   
@@ -1846,22 +1846,16 @@
 , result
-.count
 ))%0A%0A    

Fix some error handling.