import random

import disnake
from disnake import OptionChoice, Option, OptionType, Member, VoiceState, ApplicationCommandInteraction
from disnake.ext import commands

from integral_lib.ListGenerator import ListGenerator
from integral_lib.Logger import logger
from integral_lib.Player import play_audio


class Audio(commands.Cog, name='Audio'):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        logger.info(f'Cog {__name__.split(".")[1]} is ready!.')

    @commands.Cog.listener()
    async def on_voice_state_update(self, member: Member,
                                    before: VoiceState,
                                    after: VoiceState):
        if before.channel is None and not member.bot:
            logger.info(f'Coneccted {member.name} to {after.channel.name}')
            if any('Escape from Tarkov' in str(user.activity) for user in after.channel.members):
                logger.info('Skip playing by Game')
            else:
                # Prepare list of audio
                from integral_lib.Comands import read_json
                _role = await read_json(member.guild.id, 'tigger_role')
                audio: list = []
                for _a in ListGenerator('audio'):
                    audio.append(_a.name)

                if len(member.roles) == 1 or _role is None:
                    logger.info('Skip playing by role')
                elif any(str(role.id) in _role for role in member.roles):
                    logger.info('Play audio from list by role')
                    await play_audio(f'audio/{random.choice(audio)}', self.bot, after.channel)
                else:
                    logger.info('Skip playing by any else')

    @commands.slash_command(name="play_audio",
                            description="Make possible playing audio by command",
                            options=[
                                Option(name="audio",
                                       type=OptionType.string,
                                       required=True
                                       )
                            ])
    async def playaudio(self, inter: disnake.ApplicationCommandInteraction,
                        audio: str
                        ):
        if inter.author.voice is not None:
            await inter.response.send_message(f'Played {audio}', ephemeral=True)
            await play_audio(audio, self.bot, inter.author.voice.channel)
        else:
            await inter.response.send_message('You`re not in voice', ephemeral=True)

    @playaudio.autocomplete('audio')
    async def list_to_play(self, inter: ApplicationCommandInteraction, current: str):
        """
        Asynchronously generates a list of OptionChoices for the given audio files based on the user input.
        Parameters:
        - inter: disnake.ApplicationCommandInteraction - The interaction context for the command.
        - current: str - The current user input to filter the audio file choices.
        Returns:
        - list[OptionChoice] - A list of OptionChoice objects representing the available audio file choices.
        :param current:
        :param inter: ApplicationCommandInteraction
        """
        current = current.lower()
        _dict: dict = {}
        for f in ListGenerator('audio'):
            _dict[f.name] = f'{f.path}/{f.name}'
        return [
            OptionChoice(name=choice, value=f'{_dict[choice]}')
            for choice in _dict if current in choice.lower()
        ]


def setup(bot):  # an extension must have a setup function
    bot.add_cog(Audio(bot))  # adding a cog
