import os

import df2img
import disnake
import pandas as pd
from PIL import Image

import discordbot.config_discordbot as cfg
from discordbot.config_discordbot import logger
from discordbot.helpers import autocrop_image
from gamestonk_terminal.economy import wsj_model


async def currencies_command(ctx):
    """Currencies overview [Wall St. Journal]"""

    try:
        # Debug user input
        if cfg.DEBUG:
            logger.debug("econ-currencies")

        # Retrieve data
        df = wsj_model.global_currencies()
        df = pd.DataFrame.from_dict(df)

        # Check for argument
        if df.empty:
            raise Exception("No available data found")

        df["Last"] = pd.to_numeric(df["Last"].astype(float))
        df["Chng"] = pd.to_numeric(df["Chng"].astype(float))
        df["%Chng"] = pd.to_numeric(df["%Chng"].astype(float))

        formats = {"Last": "{:.2f}", "Chng": "{:.2f}", "%Chng": "{:.2f}%"}
        for col, value in formats.items():
            df[col] = df[col].map(lambda x: value.format(x))  # pylint: disable=W0640

        df = df.fillna("")
        df.set_index(" ", inplace=True)

        # Debug user output
        if cfg.DEBUG:
            logger.debug(df.to_string())

        df = df[
            [
                "Last",
                "Chng",
                "%Chng",
            ]
        ]
        dindex = len(df.index)
        fig = df2img.plot_dataframe(
            df,
            fig_size=(800, (40 + (40 * dindex))),
            col_width=[8, 3, 3],
            tbl_cells=dict(
                align="left",
                height=35,
            ),
            template="plotly_dark",
            font=dict(
                family="Consolas",
                size=20,
            ),
            paper_bgcolor="rgba(0, 0, 0, 0)",
        )

        imagefile = "econ-currencies.png"
        df2img.save_dataframe(fig=fig, filename=imagefile)
        image = Image.open(imagefile)
        image = autocrop_image(image, 0)
        image.save(imagefile, "PNG", quality=100)

        image = disnake.File(imagefile)

        title = "Economy: [WSJ] Currencies"
        embed = disnake.Embed(title=title, colour=cfg.COLOR)
        embed.set_image(url=f"attachment://{imagefile}")
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )
        os.remove(imagefile)

        await ctx.send(embed=embed, file=image)

    except Exception as e:
        embed = disnake.Embed(
            title="ERROR Economy: [WSJ] Currencies",
            colour=cfg.COLOR,
            description=e,
        )
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )

        await ctx.send(embed=embed, delete_after=30.0)

[((23, 13, 23, 42), 'gamestonk_terminal.economy.wsj_model.global_currencies', 'wsj_model.global_currencies', ({}, {}), '()', False, 'from gamestonk_terminal.economy import wsj_model\n'), ((24, 13, 24, 39), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', ({(24, 36, 24, 38): 'df'}, {}), '(df)', True, 'import pandas as pd\n'), ((70, 8, 70, 58), 'df2img.save_dataframe', 'df2img.save_dataframe', (), '', False, 'import df2img\n'), ((71, 16, 71, 37), 'PIL.Image.open', 'Image.open', ({(71, 27, 71, 36): 'imagefile'}, {}), '(imagefile)', False, 'from PIL import Image\n'), ((72, 16, 72, 40), 'discordbot.helpers.autocrop_image', 'autocrop_image', ({(72, 31, 72, 36): 'image', (72, 38, 72, 39): '0'}, {}), '(image, 0)', False, 'from discordbot.helpers import autocrop_image\n'), ((75, 16, 75, 39), 'disnake.File', 'disnake.File', ({(75, 29, 75, 38): 'imagefile'}, {}), '(imagefile)', False, 'import disnake\n'), ((78, 16, 78, 60), 'disnake.Embed', 'disnake.Embed', (), '', False, 'import disnake\n'), ((84, 8, 84, 28), 'os.remove', 'os.remove', ({(84, 18, 84, 27): 'imagefile'}, {}), '(imagefile)', False, 'import os\n'), ((20, 12, 20, 43), 'discordbot.config_discordbot.logger.debug', 'logger.debug', ({(20, 25, 20, 42): '"""econ-currencies"""'}, {}), "('econ-currencies')", False, 'from discordbot.config_discordbot import logger\n'), ((89, 16, 93, 9), 'disnake.Embed', 'disnake.Embed', (), '', False, 'import disnake\n')]