# -*- coding: utf-8 -*-
from datetime import datetime

import irc3
from docopt import Dict
from irc3.plugins.command import command
from irc3.utils import IrcString
from psycopg2 import Error

from . import DatabasePlugin, Bot


class Tell(DatabasePlugin):
    def __init__(self, bot: Bot):
        super().__init__(bot)
        self.tell_queue = {}

        with self.con.cursor() as cur:
            cur.execute('''
            SELECT
               to_nick, from_nick, message, created_at
            FROM
              tells
            ''')

            for res in cur.fetchall():
                nick = res['to_nick'].lower()

                if nick not in self.tell_queue:
                    self.tell_queue[nick] = []
                self.tell_queue[nick].append(res[1:])

    @command
    def tell(self, mask: IrcString, target: IrcString, args: Dict):
        """Saves a message for nick to forward on activity

        %%tell <nick> <message>...
        """
        nick = args['<nick>'].lower()
        tell = [nick, mask.nick, ' '.join(args['<message>']).strip(), datetime.utcnow()]

        try:
            with self.con.cursor() as cur:
                cur.execute('''
                INSERT INTO
                  tells (to_nick, from_nick, message, created_at)
                VALUES
                  (%s, %s, %s, %s)
                ''', tell)
            self.con.commit()
            if nick not in self.tell_queue:
                self.tell_queue[nick] = []
            self.tell_queue[nick].append(tell[1:])
            self.bot.notice(mask.nick, "I will tell that to {} when I see them.".format(nick))
        except Error as ex:
            self.log.error(ex)
            self.con.rollback()

            self.bot.notice(mask.nick, "database error (is the user already awaiting such a message?)")

    @irc3.event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*')
    def on_message(self, mask: str):
        """If activ nick has tells, forward and delete them."""
        nick = IrcString(mask).nick.lower()

        if nick in self.tell_queue:
            # Forward all tells for nick
            for tell in self.tell_queue[nick]:
                self.bot.privmsg(nick, '\x02[Tell]\x02 Message from {nick} at {time}: {message}'.format(
                    nick=tell[0],
                    time=tell[2],  # TODO: format time
                    message=tell[1],
                ))

            del self.tell_queue[nick]
            with self.con.cursor() as cur:
                cur.execute('''
                DELETE FROM
                  tells
                WHERE
                  to_nick = %s
                ''', [nick])
            self.con.commit()