from tkinter import *
from tkinter import messagebox
import mysql.connector
from obswebsocket import obsws, requests
from twitch.helix.api import TwitchHelix
from twitchAPI.helper import first
import asyncio
import twitchAPI
import webbrowser
    
class NouvelleFenetre:

    oauth_authorization_url = f"https://id.twitch.tv/oauth2/authorize?client_id={'6h883my3p6ndqozotnl6nsbllyyr3h'}&redirect_uri={'http://localhost'}&response_type=code&scope={'user_read'}"
    
    # Fonction permettant de fermer la deuxième fenetre créee et la première fenetre de connexion de se réafficher tout en se déconnecctant d'OBS
    def fermer_et_reafficher(self):
        self.root.destroy()
        self.ws.disconnect()
        self.root.master.deiconify()

    # Fonction permettant de récupérer la valeur de la clé twitch qui a été renseignée
    def get_key_twitch(self):
        self.twitch = self.entry_twitch.get()
        print (self.twitch)

    # Fonction permettant de récupérer la valeur de la clé youtube qui a été renseignée
    def get_key_youtube(self):
        self.youtube = self.entry_youtube.get()
        print (self.youtube)

    def set_key_twitch(self, username):
        try:
            # Paramètres du serveur
            cnx = mysql.connector.connect(user='root', password='',
                                        host='127.0.0.1',
                                        database='obs_project')
            cur = cnx.cursor()

            # On lance une requête pour vérifier si l'utilisateur correspond à la base de données
            query = "SELECT * FROM utilisateurs WHERE username = %s"
            cur.execute(query, (username,))

            # Renvoie la première ligne de la base de données qui correspond
            user = cur.fetchone()

            if user:
                # Utilisateur trouvé, on met à jour la clé Twitch
                new_twitch_key = self.entry_twitch.get()
                update_query = "UPDATE twitch SET twitch_key = %s WHERE username = %s"
                cur.execute(update_query, (new_twitch_key, username))
                cnx.commit()
                print(f"La clé a été mis à jour pour {username} avec la clé {new_twitch_key}")
            else:
                print(f"Utilisateur {username} non trouvée")

        except mysql.connector.Error as err:
            print(f"Erreur: {err}")
            messagebox.showerror("Erreur", "Une erreur a eu lieu pour mettre à jour votre clé")

        finally:
            # On ferme le tout, la connexion etc...
            cur.close()
            cnx.close()

    def set_key_youtube(self, username):
        try:
            # Paramètres du serveur
            cnx = mysql.connector.connect(user='root', password='',
                                        host='127.0.0.1',
                                        database='obs_project')
            cur = cnx.cursor()

            # On lance une requête pour vérifier si l'utilisateur correspond à la base de données
            query = "SELECT * FROM utilisateurs WHERE username = %s"
            cur.execute(query, (username,))

            # Renvoie la première ligne de la base de données qui correspond
            user = cur.fetchone()

            if user:
                # Utilisateur trouvé, on met à jour la clé Twitch
                new_youtube_key = self.entry_youtube.get()
                update_query = "UPDATE youtube SET youtube_key = %s WHERE username = %s"
                cur.execute(update_query, (new_youtube_key, username))
                cnx.commit()
                print(f"La clé a été mis à jour pour {username} avec la clé {new_youtube_key}")
            else:
                print(f"Utilisateur {username} non trouvée")

        except mysql.connector.Error as err:
            print(f"Erreur: {err}")
            messagebox.showerror("Erreur", "Une erreur a eu lieu pour mettre à jour votre clé")

        finally:
            # On ferme le tout, la connexion etc...
            cur.close()
            cnx.close()

    def get_twitch_key_from_database(self, username):
        try:
            # Paramètres du serveur
            cnx = mysql.connector.connect(user='root', password='',
                                        host='127.0.0.1',
                                        database='obs_project')
            cur = cnx.cursor()

            # On lance une requête pour récupérer la clé Twitch de l'utilisateur
            query = "SELECT twitch_key FROM twitch WHERE username = %s"
            cur.execute(query, (username,))
            twitch_key = cur.fetchone()

            if twitch_key:
                return twitch_key[0]
            else:
                print(f"Clé Twitch non trouvée pour l'utilisateur {username}")
                return None

        except mysql.connector.Error as err:
            print(f"Erreur: {err}")
            messagebox.showerror("Erreur", "Une erreur a eu lieu pour récupérer la clé Twitch")

        finally:
            # On ferme le tout, la connexion etc...
            cur.close()
            cnx.close()

    # On configure OBS pour Twitch
    def configure_obs_for_twitch(self, twitch_stream_key):
        # Utilisez la clé Twitch pour configurer OBS
        self.ws.call(requests.StartStreaming(stream=twitch_stream_key))

    def boutondediffusiontwitch_callback(self):
        # Avec la variable is_twitch_streaming passé à False au commencement, on vérifie son état pour diffuser ou stoper le streaming
        if self.is_twitch_streaming:
            self.ws.call(requests.StopStreaming())
            self.is_twitch_streaming = False
        else:
            self.ws.call(requests.StartStreaming(stream= self.twitch_key_from_database))
            self.is_twitch_streaming = True

    client_id = '6h883my3p6ndqozotnl6nsbllyyr3h'
    oauth_token ='r4l2v9bgvlb0uh6cqqgw9j85tlojvd'
    login = 'iSeralestis'

    async def get_twitch_user(self, client_id, oauth_token, login):
        twitch = TwitchHelix(client_id, oauth_token)
    
        user = await first (twitch.get_users(login_names= login))
    
        return user
        
    async def initialize_twitch(self):
        twitch_user = await self.get_twitch_user(self.client_id, self.oauth_token, self.login)
        if twitch_user:
            print("Twitch user found:")
            print("ID:", twitch_user.id)
            print("Username:", twitch_user.display_name)
        else:
            print("Twitch user not found.")
      

    # Création de la nouvelle fenetre une fois l'authentification faite
    async def initialize_window(self, root, username, password):
        self.root = Toplevel(root)
        self.root.title("OBS Extension Multistreaming")
        self.root.geometry("1920x1080")

        self.lancer_auth_twitch()
        await self.initialize_twitch()

    def __init__(self, root, username, password):
        asyncio.run(self.initialize_window(root, username, password))

        self.root.grid_rowconfigure(0, weight=0)
        self.root.grid_rowconfigure(1, weight=0)
        self.root.grid_rowconfigure(2, weight=0)
        self.root.grid_rowconfigure(3, weight=0)
        self.root.grid_rowconfigure(4, weight=0)
        self.root.grid_rowconfigure(5, weight=0)
        self.root.grid_rowconfigure(6, weight=0)
        self.root.grid_rowconfigure(7, weight=0)
        self.root.grid_rowconfigure(8, weight=0)
        self.root.grid_rowconfigure(9, weight=0)
        self.root.grid_rowconfigure(10, weight=0)
        self.root.grid_rowconfigure(11, weight=0)
        self.root.grid_rowconfigure(12, weight=0)
        self.root.grid_rowconfigure(13, weight=0)
        self.root.grid_rowconfigure(14, weight=0)
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_columnconfigure(1, weight=0)
        self.root.grid_columnconfigure(2, weight=0)
        self.root.grid_columnconfigure(3, weight=0)

        # Créer un bouton pour lancer le processus d'authentification Twitch
        bouton_auth_twitch = Button(self.root, text="Autoriser l'accès à Twitch", command=self.lancer_auth_twitch)
        bouton_auth_twitch.grid(row=15, column=0)

        # C'est mon id de ma chaine twitch identifiant Alexis
        self.client_id = '6h883my3p6ndqozotnl6nsbllyyr3h'
        self.oauth_token ='r4l2v9bgvlb0uh6cqqgw9j85tlojvd'
        self.login = 'iSeralestis'

        self.twitch_client = TwitchHelix(client_id = self.client_id, oauth_token = self.oauth_token)

        # On récupère la clé Twitch depuis la base de données
        self.twitch_key_from_database = self.get_twitch_key_from_database(username)


        # Initialisez la connexion OBS WebSocket
        self.ws = obsws("localhost", 4455, "MPcZLZfViZihHqmg")
        self.ws.connect()

        # Configurez les paramètres de diffusion pour Twitch (remplacez 'stream_key' par le nom correct de votre champ)
        twitch_stream_key = self.get_twitch_key_from_database(username)  # Variable qui récupére la key
        self.configure_obs_for_twitch(twitch_stream_key)

        # On affiche bienvenue à la personne s'étant identifiée, en récupérant la variable lastname
        label = Label(self.root, text=f"Bienvenue, {username}!")
        label.grid(row = 0, column = 0)

        label = Label(self.root, text = "Clé Twitch :")
        label.grid(row = 2, column = 0)

        self.entry_twitch = Entry(self.root)
        self.entry_twitch.grid(row= 3, column = 0)


        # On met un bouton de validation pour garder les valeurs qu'on a rentré précédement
        boutonvalidation = Button(self.root, text="Envoyé", command= lambda : self.set_key_twitch(username))
        boutonvalidation.grid(row = 4, column = 0)

        # On met d'office cette variable à False pour dire qu'on ne stream pas au lancement de l'application
        self.is_twitch_streaming = False

        # On met un bouton de diffusion pour twitch
        boutondediffusiontwitch = Button(self.root, text="Diffusion de Twitch On/Off", command=self.boutondediffusiontwitch_callback)
        boutondediffusiontwitch.grid(row = 4, column = 3)

        label = Label(self.root, text = "Clé Youtube :")
        label.grid(row = 5, column = 0)

        self.entry_youtube = Entry(self.root)
        self.entry_youtube.grid(row = 6, column = 0)

        # On met un bouton pour envoyer les valeurs remplies du dessus
        boutonvalidation2 = Button(self.root, text="Envoyé", command= lambda :self.set_key_youtube(username))
        boutonvalidation2.grid(row = 7, column = 0)

        # On met un bouton de diffusion pour twitch
        boutondediffusionyoutube = Button(self.root, text="Diffusion de YouTube On/Off")
        boutondediffusionyoutube.grid(row = 7, column = 3)

        # On met un boutton fermer, pour pouvoir fermer la page main, et repasser sur la fenetre de connexion
        bouton_fermer = Button(self.root, text="Fermer", command=self.fermer_et_reafficher)
        bouton_fermer.grid(row = 13, column = 0)

    def lancer_auth_twitch(self):
        # Ouvrir le lien dans le navigateur Web par défaut
        webbrowser.open(self.oauth_authorization_url)

        # Afficher un message indiquant que l'utilisateur doit autoriser l'accès à Twitch dans le navigateur
        messagebox.showinfo("Authentification Twitch", "Veuillez autoriser l'accès à Twitch dans le navigateur Web qui s'est ouvert.")