#!/usr/bin/env python3
import asyncio
from os import getenv
from os.path import isfile

import disnake
from disnake import OptionType, Option, Localized
from disnake.ext import commands
from dotenv import load_dotenv

from __init__ import __version__
from lib.CogsPrep import work_with_cogs, cog_list
from lib.Comands import determine_prefix
from lib.Logger import logger

load_dotenv()
if not isfile('.env') or not getenv('CONF_FILE'):
    with open('.env', 'a', encoding='utf-8') as f:
        f.write("CONF_FILE='config.json'\n")
    load_dotenv()
if not isfile(getenv('CONF_FILE')):
    with open(getenv('CONF_FILE'), 'a', encoding='utf-8') as f:
        f.write("")

intents = disnake.Intents(messages=True,
                          guilds=True,
                          message_content=True,
                          voice_states=True,
                          members=True,
                          presences=True
                          )

bot = commands.Bot(command_prefix=determine_prefix,
                   intents=intents,
                   reload=True,
                   test_guilds=[648126669122568215]
                   )

bot.i18n.load("locale/")

asyncio.run(work_with_cogs('load', bot, asyncio.run(cog_list())))


@bot.event
async def on_ready():
    logger.info('Bot started')
    logger.info(f'Disnake version {disnake.__version__}')
    logger.info(f'We have logged in as {bot.user}')
    logger.info(f'Version of bot is - v{__version__}')


@bot.slash_command(
    name='cog',
    options=[
        Option(
            name=Localized('cog', key="COG".lower()),
            description=Localized("cog file", key="COG_FILE"),
            type=OptionType.string
        )
    ]
)
@commands.is_owner()
async def slash_cogs(inter: disnake.ApplicationCommandInteraction):
    """
    Working with cogs (modules) {{SLASH_COG}}

    Parameters
    ----------
    :param inter:
    """
    pass


@slash_cogs.sub_command(description=Localized("Enables Cog", key="ENABLE_COG"))
async def enable(inter: disnake.ApplicationCommandInteraction, cog: str):
    """

    Parameters
    ----------
    :param inter:
    :param cog: Select Cogfile {{COG_FILE}}
    """
    await work_with_cogs('enable', bot, cog)
    await inter.response.send_message(f'Cog {cog} is enabled', ephemeral=True)


@slash_cogs.sub_command(description=Localized("Disables Cog", key="DISABLE_COG"))
async def disable(inter: disnake.ApplicationCommandInteraction, cog: str):
    """

    Parameters
    ----------
    :param inter:
    :param cog: Select Cogfile {{COG_FILE}}
    """
    await work_with_cogs('disable', bot, cog)
    await inter.response.send_message(f'Cog {cog} is disabled', ephemeral=True)


@slash_cogs.sub_command(description=Localized("Loads Cog", key="LOAD_COG"))
async def load(inter: disnake.ApplicationCommandInteraction, cog: str):
    """

    Parameters
    ----------
    :param inter:
    :param cog: Select Cogfile {{COG_FILE}}
    """
    await work_with_cogs('load', bot, cog)
    await inter.response.send_message(f'Cog {cog} is loaded', ephemeral=True)


@slash_cogs.sub_command(description=Localized("Unload Cog", key="UNLOAD_COG"))
async def unload(inter: disnake.ApplicationCommandInteraction, cog: str):
    """

    Parameters
    ----------
    :param inter:
    :param cog: Select Cogfile {{COG_FILE}}
    """
    await work_with_cogs('unload', bot, cog)
    await inter.response.send_message(f'Cog {cog} is unload', ephemeral=True)


@slash_cogs.sub_command(description=Localized("Reloads Cog", key="RELOAD_COG"))
async def reload(inter: disnake.ApplicationCommandInteraction, cog: str):
    """

    Parameters
    ----------
    :param inter:
    :param cog: Select Cogfile {{COG_FILE}}
    """
    await work_with_cogs('reload', bot, cog)
    await inter.response.send_message(f'Cog {cog} is reloaded', ephemeral=True)


@disable.autocomplete('cog')
@unload.autocomplete('cog')
@load.autocomplete('cog')
@reload.autocomplete('cog')
async def _cog_opt(inter: disnake.ApplicationCommandInteraction, current: str):
    current = current.lower()
    _list = await cog_list(fold='./cogs/')
    return [choice for choice in _list if current in choice.lower()]


@enable.autocomplete('cog')
async def _cog_opt(inter: disnake.ApplicationCommandInteraction, current: str):
    current = current.lower()
    _list = await cog_list(fold='./cogs/disabled/')
    return [choice for choice in _list if current in choice.lower()]


@slash_cogs.error
async def cogs_error(inter: disnake.ApplicationCommandInteraction):
    await inter.response.send_message(Localized("Error", key="EROR"), ephemeral=True)
    logger.error(f'User {inter.author} tries to use cogs func')


bot.run(getenv('TOKEN'))
