#    guppy Copyright (C) 2010-2011 guppy team members.
#
#    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
#    This is free software, and you are welcome to redistribute it
#    under certain conditions; type `show c' for details.
#  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 2 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, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.

#import re
import time
#import datetime
#from datetime import datetime as dt
import os
import sqlite3


@plugin
class Seen(object):
    def __init__(self, server):
        self.server = server
        self.network = self.server.config["network"]
        self.commands = ["seen"]
        self.server.handle("command", self.handle_command, self.commands)
        server.handle("message", self.handle_message)
        self.db = os.path.join(self.server.config["confdir"], "seen.db")
        ## cam variables
        self.db_exists = os.path.isfile(self.db)
        self.connection = sqlite3.connect(self.db)
        self.cursor = self.connection.cursor()
        if not self.db_exists:
            # create the db
            self.cursor.execute('CREATE TABLE seen (nick text, timestamp text, network text, channel text, message text, UNIQUE ( nick, network ))')
            print("[DEBUG] Database created for the first time")
        else:
            # This is hacky, but I'm lazy
            self.cursor.execute('PRAGMA index_list(seen)')
            if not self.cursor.fetchone():
                # Gotta give the table the unique constraint; shifting data to a temp table so we can DROP the original, and then rename the temp table
                self.cursor.execute('CREATE TABLE seen_temp (nick text, timestamp text, network text, channel text, message text, UNIQUE ( nick, network ))')
                self.cursor.execute('INSERT INTO seen_temp SELECT * FROM seen')
                self.cursor.execute('DROP TABLE seen')
                self.cursor.execute('ALTER TABLE seen_temp RENAME TO seen')
                print("[DEBUG] Database schema updated")
        self.connection.commit()

    def handle_message(self, channel, nick, message):
        # print("Message '{0}' from '{1}' in '{2}'".format(message, nick, channel))
        # add to db
        # nick, timestamp, network, channel message
        self.cursor.execute('INSERT OR REPLACE INTO seen VALUES (?, ?, ?, ?, ?)', (nick.lower(), time.time(), self.network, channel, message))
        self.connection.commit()

    def handle_command(self, channel, user, cmd, args):
        if cmd == "seen":
            nick = args[0].lower()
            self.cursor.execute('SELECT * FROM seen WHERE nick = ? and network = ?', (nick, self.network))
            info = self.cursor.fetchone()
            if info:
                # ('gry', '2013-01-31 14:50:02.419198', 'gnu', '#guppy', '-seen gry')
                t = time.time() - float(info[1])

                minutes = int(t // 60)
                seconds = int(t % 60)
                hours = int(t // 3600)
                days = int(t // 86400)

                time_msg = "{0} days, {1} hours, {2} minutes and {3} seconds ago".format(days, hours, minutes, seconds)
                if info[3][0] == '#':
                    self.server.doMessage(channel, "%s said '%s' in %s (%s)" % (info[0], info[4], info[3], time_msg))
                else:
                    self.server.doMessage(channel, "%s talked to me %s" % (info[0], time_msg))
                # print(info);  # give the info
            else:
                self.server.doMessage(channel, "I haven't seen " + nick + ", sorry.")