# -*- coding: utf-8 -*-
import irc3
from docopt import Dict
from irc3.plugins.command import command
from irc3.utils import IrcString

from . import DatabasePlugin
from .utils import parse_int


class McManiac(DatabasePlugin):
    @command(options_first=True)
    def mcmaniac(self, mask: IrcString, target: IrcString, args: Dict):
        """Get a random McManiaC or by index.

        %%mcmaniac [<index>]
        """
        index = args.get('<index>')

        if index:
            index = parse_int(index)
            if not index:
                return
            index, order = index
            order = 'id {order}'.format(order=order)
            offset = 'OFFSET %s'
        else:
            order = 'random()'
            offset = ''

        # Fetch result from database
        with self.con.cursor() as cur:
            cur.execute('''
            SELECT
              item,
              rank() OVER (ORDER BY id),
              count(*) OVER (ROWS BETWEEN UNBOUNDED PRECEDING
                                      AND UNBOUNDED FOLLOWING) AS total
            FROM
              mcmaniacs
            ORDER BY
              {order}
            LIMIT
              1
            {offset}
            '''.format(order=order, offset=offset), [index])
            result = cur.fetchone()

            if result:
                return '[{rank}/{total}] {item}'.format(**result)

    @irc3.event(r'^:(?P<mask>\S+) PRIVMSG \S+ :.*?\b(?P<item>Mc\S+iaC)\b.*')
    def save(self, mask: str, item: str):
        if IrcString(mask).nick != self.bot.nick:
            with self.con.cursor() as cur:
                cur.execute('''
                INSERT INTO
                  mcmaniacs (item)
                VALUES
                  (%s)
                ON CONFLICT DO NOTHING
                ''', [item])
            self.con.commit()