"""
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()
            except sqlite3.Error as e:
                db.rollback()
                print("sqlite error: " + str(e))
                raise

    def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
        whats = what.split(' ')

        if whats[0] == 'facts' and len(whats) >= 2:
            db = self.get_db()
            try:
                cur = db.cursor()
                if len(whats) == 2:
                    category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=?', (whats[1],))
                else:
                    # before doing a query, see if this is actually an add attempt
                    if whats[1] == 'add' and len(whats) >= 4:
                        cur.execute('''INSERT INTO facts_facts (category, fact, who, userhost)
                            VALUES (?, ?, ?, ?)''', (whats[2], ' '.join(whats[3:]), nick, userhost))
                        db.commit()
                        return self.reply(connection, replypath, "fact added")
                    else:
                        category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=? AND fact REGEXP ?', (whats[1], ' '.join(whats[2:])))
                facts = category_facts.fetchall()

                if len(facts) > 0:
                    fact = facts[random.randint(1,len(facts))-1]

                    # success
                    return self.reply(connection, replypath, fact['fact'].rstrip().encode('utf-8', 'ignore'))

            except sqlite3.Error as e:
                return self.reply(connection, replypath, "sqlite error: " + str(e))

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