"""
Facts - display facts, from within a category, from the database
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 random
import re
import sqlite3

from extlib import irclib

from Module import Module

class Facts(Module):

    """Select a fact from the database.

    Facts are categorized by a name, which may allow for random selection and so on.
    """

    def db_init(self):
        """Initialize database tables."""

        # init the database if module isn't registered
        version = self.db_module_registered(self.__class__.__name__)
        if version == None:
            db = self.get_db()
            try:
                db.execute('''
                    CREATE TABLE facts_facts (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        category TEXT NOT NULL,
                        fact TEXT NOT NULL,
                        who TEXT NOT NULL,
                        userhost TEXT NOT NULL,
                        time TEXT DEFAULT CURRENT_TIMESTAMP
                    )
                    ''')
                db.execute('INSERT INTO drbotzo_modules VALUES (?,?)', (self.__class__.__name__, 1))
                db.commit()
                db.close()
            except sqlite3.Error as e:
                db.rollback()
                db.close()
                print("sqlite error: " + str(e))
                raise

    def do(self, connection, event, nick, userhost, what, admin_unlocked):
        """Add or retrieve a fact from the database."""

        try:
            db = self.get_db()
            cur = db.cursor()

            match = re.search('^!facts\s+add\s+(\S+)\s+(.*)$', what)
            if match:
                category = match.group(1)
                fact = match.group(2)
                cur.execute('''INSERT INTO facts_facts (category, fact, who, userhost)
                               VALUES (?, ?, ?, ?)''', (category, fact, nick, userhost))
                db.commit()
                return self.reply(connection, event, category + ' added.')

            match = re.search('^!facts\s+(\S+)\s+(.*)$', what)
            if match:
                category = match.group(1)
                regex = match.group(2)
                category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=? AND fact REGEXP ?', (category, regex))
                facts = category_facts.fetchall()
                if len(facts) > 0:
                    fact = facts[random.randint(1,len(facts))-1]
                    return self.reply(connection, event, fact['fact'].rstrip().encode('utf-8', 'ignore'))

            match = re.search('^!facts\s+(\S+)$', what)
            if match:
                category = match.group(1)
                category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=?', (category,))
                facts = category_facts.fetchall()
                if len(facts) > 0:
                    fact = facts[random.randint(1,len(facts))-1]
                    return self.reply(connection, event, fact['fact'].rstrip().encode('utf-8', 'ignore'))
            db.close()
        except sqlite3.Error as e:
            db.close()
            return self.reply(connection, event, "sqlite error: " + str(e))

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