import json  # Used by long_strings(), get_params() and make_files()
import logging  # Used for logging
import os  # Used by make_files() to check if files exist
import sys  # Used to specify printing for logging

# All of this is logging configuration
FORMAT = " %(asctime)s | %(name)-16s | %(levelname)-8s | %(message)s"
PRINTFORMAT = "%(asctime)s - %(message)s"
DATEFORMAT = "%Y-%m-%d %H:%M:%S"

logging.addLevelName(25, "PRINT")
loggingConfigParams = {
    "format": FORMAT,
    "datefmt": DATEFORMAT,
    "level": logging.INFO,
    "filename": "gwendolyn.log"
}
logging.basicConfig(**loggingConfigParams)
logger = logging.getLogger("Gwendolyn")
printer = logging.getLogger("printer")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(fmt=PRINTFORMAT, datefmt=DATEFORMAT))
printer.addHandler(handler)
printer.propagate = False

def get_params():
    """
    Get the slash command parameters.

    *Returns*
    ---------
        params: dict
            The parameters for every slash command.
    """
    path = "gwendolyn/resources/slash_parameters.json"
    with open(path, "r", encoding="utf-8") as file_pointer:
        slash_parameters = json.load(file_pointer)

    return slash_parameters

PARAMS = get_params()

def log(messages, channel: str = "", level: int = 20):
    """
    Log something in Gwendolyn's logs.

    *Parameters*
    ------------
        messages: Union[str, list]
            A string or list of strings to be logged. If there are
            multiple strings and the level is PRINT (25) or higher,
            only the first string will be printed.
        channel: str = ""
            The channel the event to be logged occurred in. Will be
            logged along with the message(s).
        level: int = 20
            The level to log the message(s) at. If PRINT (25) or
            higher, the first message will be printed to the console.
    """
    channel = channel.replace("Direct Message with ", "")
    if isinstance(messages, str):
        messages = [messages]

    print_message = messages[0]

    for i, message in enumerate(messages):
        if channel != "":
            messages[i] = f"{message} - ({channel})"  # Adds channel ID
            # to log messages

    if len(messages) > 1:  # Tells user to check the log if there are
        # more messages there
        print_message += " (details in log)"

    if level >= 25:
        printer.log(level, print_message)

    for log_message in messages:
        logger.log(level, log_message)

def make_files():
    """Create all the files and directories needed by Gwendolyn."""
    def make_json_file(path, content):
        """Create json file if it doesn't exist."""
        if not os.path.isfile(path):
            log(path.split("/")[-1]+" didn't exist. Making it now.")
            with open(path, "w", encoding="utf-8") as file_pointer:
                json.dump(content, file_pointer, indent=4)

    def make_txt_file(path, content):
        """Create txt file if it doesn't exist."""
        if not os.path.isfile(path):
            log(path.split("/")[-1]+" didn't exist. Making it now.")
            with open(path, "w", encoding="utf-8") as file_pointer:
                file_pointer.write(content)

    def directory(path):
        """Create directory if it doesn't exist."""
        if not os.path.isdir(path):
            os.makedirs(path)
            log("The "+path.split("/")[-1]+" directory didn't exist")

    file_path = "gwendolyn/resources/starting_files.json"
    with open(file_path, "r", encoding="utf-8") as file_pointer:
        data = json.load(file_pointer)

    for path in data["folder"]:
        directory(path)

    for path, content in data["json"].items():
        make_json_file(path, content)

    for path, content in data["txt"].items():
        make_txt_file(path, content)

