#!/usr/bin/python

import sys
import getopt
import dbus
from spambayes.Options import options

GCONF_DIR = '/apps/evolution/mail/junk/spambayes'
GCONF_TRAIN_ON_ALL_MESSAGES = GCONF_DIR + '/train_on_all_messages'
GCONF_HAM_CUTOFF = GCONF_DIR + '/ham_cutoff'
GCONF_SPAM_CUTOFF = GCONF_DIR + '/spam_cutoff'

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'shupfxc')
    except getopt.error, msg:
        print msg
        return -1
    
    train = False
    train_spam = False
    untrain = False
    ping = False
    filter = False
    exit = False
    clues = False
    
    for opt, arg in opts:
        if opt == '-s':
            train = True
            train_spam = True
        elif opt == '-h':
            train = True
            train_spam = False
        elif opt == '-u':
            untrain = True
        elif opt == '-p':
            ping = True
        elif opt == '-f':
            filter = True
        elif opt == '-x':
            exit = True
        elif opt == '-c':
            clues = True
    
    bus = dbus.SessionBus ()
    server_obj = None
    server = None
    try:
        server_obj = bus.get_object ('net.halfdans.Spam', '/net/halfdans/SpamBayes')
        server = dbus.Interface ( server_obj, 'net.halfdans.Spam' )
        if ping:
            return server.ping()
        elif exit:
            return server.exit()
    
    except Exception, e:
        print e
        return -1
    
    try:
        # Read the message from stdin
        
        msg = sys.stdin.read()
        try:
            # Try decoding data as unicode
            msg = unicode(msg, 'utf-8')
            
        except:
            
            try:
                # otherwise try iso-8859-1
                msg = unicode(msg, 'iso-8859-1')
            except:
                # as a last resort, we just filter out the characters outside the range
                newmsg = u''
                for c in msg:
                    if ord(c) < 128:
                        newmsg += u'%c' % ord(c)
                msg = newmsg
        
        # Then we convert from unicode back to str with utf-8 encoding
        msg = msg.encode('utf-8')
        
        if untrain:
            server.untrain(msg, train_spam)
        
        elif train:
            server.train(msg, train_spam)
        
        elif filter:
            msg = server.filter(msg)
            print ''.join([str(s) for s in msg])
            return 0
        
        elif clues:
            clues = server.clues(msg)
            for clue, score in clues:
                print clue, score
            return 0
        
        else:
            import gconf
            client = gconf.client_get_default ()
            score = server.score(msg)
            if score < client.get_float(GCONF_HAM_CUTOFF):
                return 0
            elif score > client.get_float(GCONF_SPAM_CUTOFF):
                return 2
            # We need to return a non-zero value to say "not spam", so rather than return a special value for unsure we return 0.
            return 1
    
    except:
        import traceback
        traceback.print_exc()
    return -1

status = main()
sys.exit(status)
