from dataclasses import dataclass
from nonebot.internal.adapter import Event

from nonebot.adapters.onebot.v11 import Event as OB11Event
from nonebot.adapters.onebot.v11.event import GroupMessageEvent as OB11GroupEvent
from nonebot.adapters.onebot.v11.event import PrivateMessageEvent as OB11PrivateEvent

from nonebot.adapters.discord.event import Event as DiscordEvent
from nonebot.adapters.discord.event import GuildMessageCreateEvent as DiscordGMEvent
from nonebot.adapters.discord.event import DirectMessageCreateEvent as DiscordDMEvent

from nonebot.adapters.minecraft.event import MessageEvent as MinecraftMessageEvent

from nonebot.adapters.console.event import MessageEvent as ConsoleEvent


@dataclass(frozen=True)
class PermEntity:
    platform: str
    entity_type: str
    external_id: str


def get_entity_chain_of_entity(entity: PermEntity) -> list[PermEntity]:
    return [
        PermEntity("sys", "global", "global"),
        PermEntity(entity.platform, "global", "global"),
        entity,
    ][::-1]


async def get_entity_chain(event: Event) -> list[PermEntity]:  # pragma: no cover
    entities = [PermEntity("sys", "global", "global")]

    if isinstance(event, OB11Event):
        entities.append(PermEntity("ob11", "global", "global"))

    if isinstance(event, OB11GroupEvent):
        entities.append(PermEntity("ob11", "group", str(event.group_id)))
        entities.append(PermEntity("ob11", "user", str(event.user_id)))

    if isinstance(event, OB11PrivateEvent):
        entities.append(PermEntity("ob11", "user", str(event.user_id)))

    if isinstance(event, DiscordEvent):
        entities.append(PermEntity("discord", "global", "global"))

    if isinstance(event, DiscordGMEvent):
        entities.append(PermEntity("discord", "guild", str(event.guild_id)))
        entities.append(PermEntity("discord", "channel", str(event.channel_id)))
        entities.append(PermEntity("discord", "user", str(event.user_id)))

    if isinstance(event, DiscordDMEvent):
        entities.append(PermEntity("discord", "channel", str(event.channel_id)))
        entities.append(PermEntity("discord", "user", str(event.user_id)))

    if isinstance(event, MinecraftMessageEvent):
        entities.append(PermEntity("minecraft", "global", "global"))
        entities.append(PermEntity("minecraft", "server", event.server_name))
        player_uuid = event.player.uuid
        if player_uuid is not None:
            entities.append(PermEntity("minecraft", "player", player_uuid.hex))

    if isinstance(event, ConsoleEvent):
        entities.append(PermEntity("console", "global", "global"))
        entities.append(PermEntity("console", "channel", event.channel.id))
        entities.append(PermEntity("console", "user", event.user.id))

    return entities[::-1]
