"""
lib.Commands
~~~~~~~~~~~~~~
Some prepare for commands
"""
import json
import os
import dotenv


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


async def list_files(fold: str = 'audio'):
    if fold != 'audio': fold = f'audio/{fold}'
    fl = []
    for filenames in os.walk(fold):
        fl.extend(filenames)
        break
    files = {}
    for x in fl[2]:
        files[x] = x
    return fl[2]


async def read_json(guild: int, _param: str):
    """
    Reads Json file to determite config strings
    :param guild: ID of Guild
    :param _param: Parameter in json file
    :return: value of parameter.
    """
    parameter = None
    with open(os.getenv('CONF_FILE'), encoding='utf-8') as f:  # Open the JSON
        try:
            _json = json.load(f)  # Load the custom prefixes
        except json.decoder.JSONDecodeError:
            _json = {}
    if guild:  # If the guild exists
        try:
            guild_conf = _json[f"{guild}"]
            try:
                parameter = guild_conf[f"{_param}"]
            except KeyError:
                pass
        except KeyError:
            pass
    return parameter


async def write_json(guild: int, param_name: str, param: str or int):
    with open(os.getenv('CONF_FILE'), encoding='utf-8') as f:
        try:
            _json = json.load(f)
        except json.decoder.JSONDecodeError:
            _json = {}
    try:
        _guild = _json[f'{guild}']
    except KeyError:
        _json.update({f'{guild}': {}})
    _guild = _json[f'{guild}']
    _guild.update({f'{param_name}': f'{param}'})
    with open(os.getenv('CONF_FILE'), 'w', encoding='utf-8') as f:
        json.dump(_json, f, indent=4)


def determine_prefix(bot, msg):
    """
    Determite per-server bot prefix
    :param bot: Disnake Bot object
    :param msg: Disnake msg object
    :return: prefix for server, default is $
    """
    parameter = '$'
    with open(os.getenv('CONF_FILE'), encoding='utf-8') as f:  # Open the JSON
        try:
            _json = json.load(f)  # Load the custom prefixes
        except json.JSONDecodeError:
            _json = {}
    try:
        parameter = _json[f"{msg.guild.id}"]["prefix"]  # Read prefix from json if is setted up

    except KeyError:
        pass
    return parameter


def determine_time(msg):
    """
    Determite per-server bot prefix
    :param msg: Disnake msg object
    :return: prefix for server, default is $
    """
    parameter = 15
    with open(os.getenv('CONF_FILE'), encoding='utf-8') as f:  # Open the JSON
        try:
            _json = json.load(f)  # Load the custom prefixes
        except json.JSONDecodeError:
            _json = {}
    try:
        parameter = _json[f"{msg.guild.id}"]["seconds"]  # Read prefix from json if is setted up

    except KeyError:
        pass
    return parameter
