import random
import re
from datetime import datetime, timedelta

from rollbot import as_command, Message, RollbotFailure, Command, Attachment
from rollbot.injection import (
    ChannelAdmin,
    OriginAdmin,
    Debugging,
    Args,
    SenderName,
    ArgList,
    Config,
)


@as_command
def isadmin(channel: ChannelAdmin, origin: OriginAdmin):
    return f"Channel: {channel}, Origin: {origin}"


@as_command
def debug(message: Message, debugging: Debugging):
    return f"{message}\nLast Error: {debugging}"


@as_command
def echo(body: Args, name: SenderName):
    return f"'{body}' - {name}"


@as_command
def greet():
    return random.choice(("Hi!", "Hello!", "안녕하세요", "こんにちは", "你好", "👋"))


@as_command
def console(argstr: Args):
    opts = ["NEVER GIVE UP", "I believe in you!", "You're doing your best, it's okay!"]
    if len(argstr) > 0:
        opts.append("It'll be okay, {}! Keep trying!".format(argstr))
    return random.choice(opts)


@as_command
def choice(args: Args, arg_list: ArgList):
    for delim in ("|", ";", ","):
        if delim in args:
            opts = args.split(delim)
            break
    else:
        opts = arg_list
    chosen = random.choice(opts).strip()
    return f"Randomly chose {chosen} from {len(opts)} options"


@as_command
def inquire():
    opts = (
        "Yes",
        "No",
        "Maybe",
        "Perhaps",
        "I guess",
        "Probably shouldn't",
        "Ask again later",
        "u know ;)",
        "rand",
    )
    chosen = random.choice(opts)
    if chosen == "rand":
        chosen = str(random.randrange(10))
    return chosen


@as_command
def democracy(candidates: Config("democracy.candidates")):
    return f"Congratulations to {random.choice(candidates)}, thank you all for participating in the democratic process!"


@as_command
def shuffle(opts: ArgList):
    if len(opts) < 2:
        return f"You need more things to shuffle!"
    random.shuffle(opts)
    fmt = "\n".join(f"{i + 1} - {v}" for i, v in enumerate(opts))
    return "Random Order:\n" + fmt


THE_GUY = """\
🖕     😎
🐛💤👔🐛
        ⛽  👢
       ⚡8=👊=D💦
   🎸     🌽
👢           👢
"""


@as_command("hey")
def the_guy(args: ArgList):
    for x, y in zip(args, ("can", "i", "have", "the", "guy")):
        if x.lower() != y:
            RollbotFailure.INVALID_ARGUMENTS.raise_exc()
    return THE_GUY


HOUSE_TOP = """\
┏┓
┃┃╱╲ In this
┃╱╱╲╲ house
╱╱╭╮╲╲ we love
▔▏┗┛▕▔ & appreciate
╱▔▔▔▔▔▔▔▔▔▔╲
"""

STFU_TOP = """\
┏┓
┃┃╱╲ Shut
┃╱╱╲╲ The
╱╱╭╮╲╲ Fuck
▔▏┗┛▕▔  Up
╱▔▔▔▔▔▔▔▔▔▔╲
"""

HOUSE_BOT = """
╱╱┏┳┓╭╮┏┳┓ ╲╲
▔▏┗┻┛┃┃┗┻┛▕▔
"""


@as_command
def appreciate(args: Args):
    return HOUSE_TOP + (" " * (20 - len(args))) + args + HOUSE_BOT


@as_command
def stfu(args: Args):
    return STFU_TOP + (" " * (20 - len(args))) + args + HOUSE_BOT


@as_command
def meme():
    return "I love you." if random.randint(1, 20) == 20 else "fuck off"


Fs = """
FFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFF
FFFFFFF
FFFFFFF
FFFFFFF
FFFFFFFFFFFFFF
FFFFFFFFFFFFFF
FFFFFFFFFFFFFF
FFFFFFF
FFFFFFF
FFFFFFF
FFFFFFF
FFFFFFF
""".strip()


@as_command("f")
def finchat(cmd: Command):
    return "frick!" if cmd.raw_name == "f" else Fs


@as_command
def reply(msg: Message):
    return "Replying!", Attachment(name="reply", body=msg.message_id)


last_feed = None
hungry_messages = ("Oh fuck yes it's a little bowl of seeds for me", "Yippee!", "Thank you for the seeds!")
not_hungry_messages = (hungry_messages[0], "Ooh even more seeds for me")


@as_command
def feed():
    global last_feed
    now = datetime.now()
    msg = random.choice(
        hungry_messages
        if last_feed is None or now - last_feed > timedelta(days=1)
        else not_hungry_messages
    )
    last_feed = now
    return msg


@as_command
def unfeed():
    global last_feed
    last_feed = None
    return random.choice(("What's your problem?", "Bro why", "Come on!!!!"))


@as_command
def bubblewrap(args: Args):
    try:
        c, r = re.match(r"(\d+)(?:[x,; ]+(\d+))?", args).groups()
        print(c, r)
        c = int(c)
        print(c, r)
        r = int(r) if r else c
        print(c, r)
    except:
        c = r = 4
    print(c, r)

    if c > 10 or r > 10:
        return "fuck off"

    return "\n".join(["||pop|| " * c] * r)
