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)

[((496, 525), 'gamestonk_terminal.economy.wsj_model.global_currencies', 'wsj_model.global_currencies', ([], {}), '()\n', (523, 525), False, 'from gamestonk_terminal.economy import wsj_model\n'), ((539, 565), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['df'], {}), '(df)\n', (561, 565), True, 'import pandas as pd\n'), ((1860, 1910), 'df2img.save_dataframe', 'df2img.save_dataframe', ([], {'fig': 'fig', 'filename': 'imagefile'}), '(fig=fig, filename=imagefile)\n', (1881, 1910), False, 'import df2img\n'), ((1927, 1948), 'PIL.Image.open', 'Image.open', (['imagefile'], {}), '(imagefile)\n', (1937, 1948), False, 'from PIL import Image\n'), ((1965, 1989), 'discordbot.helpers.autocrop_image', 'autocrop_image', (['image', '(0)'], {}), '(image, 0)\n', (1979, 1989), False, 'from discordbot.helpers import autocrop_image\n'), ((2057, 2080), 'disnake.File', 'disnake.File', (['imagefile'], {}), '(imagefile)\n', (2069, 2080), False, 'import disnake\n'), ((2142, 2186), 'disnake.Embed', 'disnake.Embed', ([], {'title': 'title', 'colour': 'cfg.COLOR'}), '(title=title, colour=cfg.COLOR)\n', (2155, 2186), False, 'import disnake\n'), ((2364, 2384), 'os.remove', 'os.remove', (['imagefile'], {}), '(imagefile)\n', (2373, 2384), False, 'import os\n'), ((426, 457), 'discordbot.config_discordbot.logger.debug', 'logger.debug', (['"""econ-currencies"""'], {}), "('econ-currencies')\n", (438, 457), False, 'from discordbot.config_discordbot import logger\n'), ((2478, 2569), 'disnake.Embed', 'disnake.Embed', ([], {'title': '"""ERROR Economy: [WSJ] Currencies"""', 'colour': 'cfg.COLOR', 'description': 'e'}), "(title='ERROR Economy: [WSJ] Currencies', colour=cfg.COLOR,\n    description=e)\n", (2491, 2569), False, 'import disnake\n')]