import requests
import io
import json
import interactions
import pandas as pd
import matplotlib.pyplot as plt
import config

user_count_url = "http://velconnect2.ugavel.com/api/get_user_count"

guild_ids = [706393774804303924, 630847214511587328]


bot = interactions.Client(config.bot_token)
bot.load('interactions.ext.files')
# bot.load('interactions.ext.enhanced')


@bot.event
async def on_ready():
    print("Ready!")


@bot.command(
    name="convrged_count",
    description="Shows a graph with the current user count in conVRged.",
    scope=706393774804303924,
    # options=[
    #     interactions.Option(
    #         name="hours",
    #         description="Number of hours of history to include. The default is 24 hours.",
    #         option_type=interactions.OptionType.NUMBER,
    #         required=False
    #     ),
    # ],
)
async def _convrged_count(ctx: interactions.CommandContext, hours: float = 24):
    await ctx.defer()
    data = get_user_count(hours)

    await post_graph(pd.DataFrame(data), ctx, f"Last {hours} hours:")


def get_user_count(graph_hours=24):
    r = requests.get(user_count_url, params={'hours': graph_hours})

    if r.status_code != 200:
        return -1
    else:
        return json.loads(r.text)


async def post_graph(df, ctx, length_message, scatter=False):
    if len(df) > 0:
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        df.columns = ['Time', 'Player Count']

        df = df[df['Player Count'] >= 0]

        params = {"ytick.color": "w",
                  "xtick.color": "w",
                  "axes.labelcolor": "w",
                  "axes.edgecolor": "w"}
        plt.rcParams.update(params)
        fig = plt.figure(figsize=(7, 3), dpi=200)
        ax = plt.axes()
        plt.margins(x=0)

        if scatter:
            plt.scatter(x=df['Time'], y=df['Player Count'],
                        alpha=.1, s=.5, c='w')
        else:
            df.plot(ax=ax, x='Time', y='Player Count', linewidth=3.0, c='w')
            # ax.step(df['Time'], df['Player Count'], linewidth=3.0, c='w')
            ax.get_legend().remove()

        ax.get_xaxis().set_visible(False)
        # ax.get_legend().remove()

        plt.savefig('graph.png', transparent=True, bbox_inches='tight')
        plt.draw()
        plt.clf()
        plt.close("all")

        with open('graph.png') as f:
            await ctx.send(content=f"Player Count: **{df.iloc[-1]['Player Count']:,.0f}**\n{length_message}", files=interactions.File(filename='graph.png', fp=f))
    else:
        await ctx.channel.send('No players :(')




@bot.command(
    name="file",
    description="Send a message as a text file",
    scope = 706393774804303924,
    options=[
        interactions.Option(
            type=interactions.OptionType.STRING,
            name="message",
            description="Message",
            required=True
        )
    ]
)
async def _file(ctx: interactions.CommandContext, message: str):
    file = io.StringIO(message)
    with file as f:
        file = interactions.File(filename="message.txt", fp=f)
        await ctx.send(files=file)




bot.start()
