from __future__ import annotations

import re
import typing as t

import snekcord as s

if t.TYPE_CHECKING:
    from ..commands.context import Context

__all__ = ("CONVERTERS",)


class TextChannel:
    @staticmethod
    async def convert(ctx: Context, string: str) -> t.Optional[s.TextChannel]:
        snowflake = s.resolvers.resolve_channel_mention(string)  # type: ignore
        if snowflake:
            print(snowflake)
            return ctx.bot.channels.get(snowflake)


class VoiceChannel:
    @staticmethod
    async def convert(ctx: Context, string: str) -> t.Optional[s.VoiceChannel]:
        snowflake = s.resolvers.resolve_channel_mention(string)  # type: ignore
        if snowflake:
            return ctx.bot.channels.get(snowflake)


class CustomEmoji:
    @staticmethod
    async def convert(ctx: Context, string: str) -> t.Optional[s.CustomEmoji]:  # type: ignore
        snowflake = s.resolvers.resolve_emoji(string)  # type: ignore
        if snowflake:
            return ctx.bot.emojis.get(snowflake["id"])


class Role:
    @staticmethod
    async def convert(ctx: Context, string: str) -> t.Optional[s.Role]:
        snowflake = s.resolvers.resolve_role_mention(string) or re.match(r"\d{1,18}", string)  # type: ignore
        if snowflake and ctx.guild:
            role = snowflake if isinstance(snowflake, s.Snowflake) else int(snowflake.group(0))  # type: ignore
            print(role)
            return ctx.guild.roles.get(role)  # type: ignore


class User:
    @staticmethod
    async def convert(ctx: Context, string: str) -> t.Optional[s.User]:
        snowflake = s.resolvers.resolve_user_mention(string) or re.match(r"\d{1,18}", string)  # type: ignore
        if snowflake:
            user = snowflake if isinstance(snowflake, s.Snowflake) else int(snowflake.group(0))  # type: ignore
            return ctx.bot.users.get(user)


class Member:
    @staticmethod
    async def convert(ctx: Context, string: str) -> t.Optional[s.GuildMember]:
        snowflake = s.resolvers.resolve_user_mention(string) or re.match(r"\d{1,18}", string)  # type: ignore
        if snowflake and ctx.guild:
            user = snowflake if isinstance(snowflake, s.Snowflake) else int(snowflake.group(0))  # type: ignore
            return ctx.guild.members.get(user)  # type: ignore


CONVERTERS = {
    s.TextChannel: TextChannel,
    s.VoiceChannel: VoiceChannel,
    s.CustomEmoji: CustomEmoji,  # type: ignore
    s.Role: Role,
    s.User: User,
    s.GuildMember: Member,
}
