"""
Seen - track when a person speaks, and allow data to be queried
Copyright (C) 2010  Brian S. Stephan

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import re

from dateutil.tz import *
import MySQLdb as mdb

from Module import Module

class Seen(Module):

    """Track when people say things in public channels, and report on it."""

    def db_init(self):
        """Create the table to store seen data."""

        version = self.db_module_registered(self.__class__.__name__)
        if version == None:
            db = self.get_db()
            try:
                version = 1
                cur = db.cursor(mdb.cursors.DictCursor)
                cur.execute('''
                    CREATE TABLE seen_nicks (
                        nick VARCHAR(64) NOT NULL,
                        location VARCHAR(64) NOT NULL,
                        host VARCHAR(256) NOT NULL,
                        time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        what LONGTEXT NOT NULL
                    ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin
                    ''')
                cur.execute('''
                    CREATE UNIQUE INDEX seen_nicks_nick_and_location_index
                        ON seen_nicks (nick, location)
                    ''')
                db.commit()
                self.db_register_module_version(self.__class__.__name__, version)
            except mdb.Error as e:
                db.rollback()
                self.log.error("database error trying to create tables")
                self.log.exception(e)
                raise
            finally: cur.close()

    def do(self, connection, event, nick, userhost, what, admin_unlocked):
        """Track pubmsg/privmsg events, and if asked, report on someone."""

        where = event.target()

        db = self.get_db()
        # whatever it is, store it
        try:
            # if there's no where, this is probably a sub-command. don't learn it
            if where:
                cur = db.cursor(mdb.cursors.DictCursor)
                statement = 'REPLACE INTO seen_nicks (nick, location, host, what) VALUES (%s, %s, %s, %s)'
                cur.execute(statement, (nick, where, userhost, what))
                db.commit()
        except mdb.Error as e:
            db.rollback()
            self.log.error("database error storing seen data")
            self.log.exception(e)
            raise
        finally: cur.close()

        match = re.search('^!seen\s+(\S+)$', what)
        if match:
            nick = match.group(1)
            db = self.get_db()
            try:
                cur = db.cursor(mdb.cursors.DictCursor)
                query = 'SELECT * FROM seen_nicks WHERE nick = %s AND location = %s'
                cur.execute(query, (nick,where))
                result = cur.fetchone()
                if result:
                    seentime = result['time'].replace(tzinfo=tzlocal())
                    replystr = 'last saw {0:s} in {3:s} at {1:s} saying \'{2:s}\'.'.format(result['nick'], seentime.astimezone(tzlocal()).strftime('%Y/%m/%d %H:%M:%S %Z'), result['what'], result['location'])
                    return self.irc.reply(event, replystr)
                else:
                    return self.irc.reply(event, 'i have not seen {0:s} in {1:s}.'.format(nick, where))
            except mdb.Error as e:
                db.rollback()
                self.log.error("database error retrieving seen data")
                self.log.exception(e)
                raise
            finally: cur.close()

# vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on;