"""
TopicDump - periodically write out the topic of channels
Copyright (C) 2013  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 MySQLdb as mdb
import os

from Module import Module

class TopicDump(Module):

    """For each topic the bot is in, output the topic to a file."""

    def db_init(self):
        """Set up the database tables, if they don't exist."""

        db = self.get_db()
        cur = db.cursor(mdb.cursors.DictCursor)
        try:
            version = self.db_module_registered(self.__class__.__name__)
            if version is None:
                version = 1
                cur.execute('''
                    CREATE TABLE topicdump_config (
                        destdir VARCHAR(255) NOT NULL
                    ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci
                    ''')

                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 register_handlers(self):
        """Hook handler functions into the IRC library."""

        self.irc.server.add_global_handler('topic', self._on_topic)

    def unregister_handlers(self):
        """Unhook handler functions from the IRC library."""

        self.irc.server.remove_global_handler('topic', self._on_topic)

    def _on_topic(self, connection, event):
        """Write topics to a file named after the source channel."""

        self.log.debug("topic change")
        self.log.debug(event.arguments()[0])
        self.log.debug(event.target())

        target_dir = self._get_destdir()
        if target_dir:
            target_file = '{0:s}.topic'.format(event.target())
            target = os.path.abspath(os.path.join(target_dir, target_file))
            self.log.debug("target file: {0:s}".format(target))

            self.log.info("writing topic to {0:s}".format(target))
            with open(target, 'w') as f:
                f.write(event.arguments()[0] + '\n')

    def _get_destdir(self):
        """Retrieve the destination directory from the database.

        Returns:
            string: the destination to write topics to

        """

        target = None
        db = self.get_db()
        cur = db.cursor(mdb.cursors.DictCursor)
        try:
            query = '''
                SELECT destdir FROM topicdump_config
                '''
            cur.execute(query, ())
            result = cur.fetchone()
            if result:
                target = result['destdir']
        except mdb.Error as e:
            self.log.error("database error while getting destination")
            self.log.exception(e)
        finally: cur.close()

        return target

# vi:tabstop=4:expandtab:autoindent