
import discord

import pandas as pd

import os
#import win32com.client as win32
#from PIL import ImageGrab
#import time
#import pythoncom
#import win32clipboard

#from datetime import date, timedelta
#import calendar
#import contextlib
    
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
#from IPython.display import Image
#from openpyxl import load_workbook



async def send_discord_notification(TOKEN, CHANNEL_ID, message, image_path=None, file_path=None):
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)

    @client.event
    async def on_ready():
        channel = client.get_channel(CHANNEL_ID)
        files = []
        Greenlight = True
        if image_path:
            if os.path.exists(image_path):
                with open(image_path, "rb") as image_file:
                    files.append(discord.File(image_file, "image.png"))
            else:
                print(f"Image file {image_path} to be sent with Discord not found")
                Greenlight=False

        if file_path: 
            if os.path.exists(file_path):
                with open(file_path, "rb") as file:
                    filename = os.path.basename(file_path)
                    files.append(discord.File(file, filename))
            else:
                print(f"File {file_path} to be sent with Discord not found")
                Greenlight=False

        if Greenlight:
            await channel.send(message, files=files)

        await client.close()
        if image_path:
            image_file.close()
        if file_path:
            file.close()

    await client.start(TOKEN)





async def generate_image(csv_file, image,  SEPARATOR):
    try:
        data = pd.read_csv(csv_file, sep=SEPARATOR)
        
        data["Cap (MUSD)"] = data["Cap (MUSD)"].apply(lambda x: f"{x / 1_000_000:,.0f}")
        data["Volat. 30 mois"] = data["Volat. 30 mois"].apply(lambda x: f"{x:.1%}")
        data["Prix"] = data["Prix"].apply(lambda x: f"{x:.2f}")
        if "MM40 sem." in data.columns:
            data["MM40 sem."] = data["MM40 sem."].apply(lambda x: f"{x:.2f}")
        if "MM10 mois" in data.columns:
            data["MM10 mois"] = data["MM10 mois"].apply(lambda x: f"{x:.2f}")
        if "Var. 13 sem." in data.columns:
            data["Var. 13 sem."] = data["Var. 13 sem."].apply(lambda x: f"{x:.1%}")
        if "Var. 3 mois" in data.columns:
            data["Var. 3 mois"] = data["Var. 3 mois"].apply(lambda x: f"{x:.1%}")


        fig, ax = plt.subplots()
        
        ax.axis('tight')
        ax.axis('off')

        # Créer un tableau avec les données formatées
        formatted_data = data.astype(str).values
        table = ax.table(cellText=formatted_data, colLabels=data.columns, cellLoc='center', loc='center')

        # Appliquer des styles à la table
        table.auto_set_font_size(False)
        table.set_fontsize(11)
        
        # Appliquer des styles aux cellules d'en-tête
        header_color = to_rgba((0 / 255, 112 / 255, 192 / 255), 1)
        for key, cell in table.get_celld().items():
            row, col = key
            if row == 0:
                cell.set_edgecolor('white')
                cell.set_facecolor(header_color)
                cell.set_text_props(fontweight='bold', color='white')

        # Appliquer des styles aux cellules de données
        row_colors = [to_rgba((227 / 255, 242 / 255, 253 / 255), 1), to_rgba((187 / 255, 222 / 255, 251 / 255), 1)]
        for row in range(1, len(data) + 1):
            for col in range(len(data.columns)):
                cell = table[row, col]
                cell.set_edgecolor('white')
                cell.set_facecolor(row_colors[row % 2])

        # Ajuster la largeur des colonnes en fonction du contenu
        """ col_widths = [max([len(str(table[row, col].get_text().get_text())) for row in range(len(data) + 1)]) for col in range(len(data.columns))]
        for col, col_width in enumerate(col_widths):
            table.auto_set_column_width(col)  """


        # Appliquer une mise en forme conditionnelle à la dernière colonne
        red_color = "FFC7CE"
        green_color = "C6EFCE"
        zero_color = "ECFAEF"
        variations_col = len(data.columns) - 1

        max_value = max(data.iloc[:, variations_col].str.replace('%', '').astype(float).max(), abs(data.iloc[:, variations_col].str.replace('%', '').astype(float).min()))
        min_value = data.iloc[:, variations_col].str.replace('%', '').astype(float).min()

        for row in range(1, len(data) + 1):
            cell = table[row, variations_col]
            value = float(data.iloc[row-1, variations_col].replace('%', ''))
            opacity = abs(value) / max_value
            opacity = max(0, min(1, opacity))  # Limite l'opacité entre 0 et 1
            
            if value == min_value:
                color = tuple(int(red_color[i:i+2], 16) / 255 for i in (0, 2, 4)) + (opacity,)
            elif value == max_value:
                color = tuple(int(green_color[i:i+2], 16) / 255 for i in (0, 2, 4)) + (opacity,)
            elif value < 0:
                color = tuple(int(red_color[i:i+2], 16) / 255 for i in (0, 2, 4)) + (opacity,)
            elif value > 0:
                color = tuple(int(green_color[i:i+2], 16) / 255 for i in (0, 2, 4)) + (opacity,)
            else:
                color = tuple(int(zero_color[i:i+2], 16) / 255 for i in (0, 2, 4)) + (1,)          

                
            cell.set_facecolor(color)


        # Supprimer la bordure de la table
        table_props = table.properties()
        table_props['edgecolor'] = 'none'
        table.scale(1.5, 1)

        # Supprimer tous les cadres et bordures
        plt.box(False)
        plt.axis('off')

        plt.savefig(image, bbox_inches='tight', pad_inches=0.1, dpi=300)
        plt.clf()
        plt.close()
        return 0
    
    except Exception:
        return -1




""" def last_working_day_of_month(year, month):
    last_day = calendar.monthrange(year, month)[1]
    last_date = date(year, month, last_day)

    # If the last day of the month is a Saturday, subtract 1 day
    if last_date.weekday() == 5:
        return last_date - timedelta(days=1)
    # If the last day of the month is a Sunday, subtract 2 days
    elif last_date.weekday() == 6:
        return last_date - timedelta(days=2)
    else:
        return last_date """


""" def is_last_working_day(date_to_check):
    year = date_to_check.year
    month = date_to_check.month
    last_working_date = last_working_day_of_month(year, month)
    return date_to_check == last_working_date """



