import requests
import streamlit as st
from streamlit_lottie import st_lottie
from PIL import Image
import subprocess
import os
import pandas as pd
# Find more emojis here: https://www.webfx.com/tools/emoji-cheat-sheet/
st.set_page_config(page_title="My Webpage", page_icon=":tada:", layout="wide")



dir = os.path.join(os.getcwd(), 'quiz')

def getAllFiles():
    return os.listdir(dir)

def load_lottieurl(url):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()


# Use local CSS
def local_css(file_name):
    with open(file_name) as f:
        st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)


local_css("style/style.css")

st.sidebar.header('Options')
file = st.sidebar.selectbox('',('Presentation','Create Quiz','Diagnostic'))
#q=st.sidebar.button('OK')



# ---- LOAD ASSETS ----
lottie_coding = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_fcfjwiyb.json")

if(file=="Presentation"):

    # ---- HEADER SECTION ----
    with st.container():
        st.subheader("Hello World :wave:")
        st.title("Espace Professeur")
        st.write(
             """
             Cette plateforme web de création de quiz avec détection de tentatives de fraude est une solution innovante pour les éducateurs, les formateurs en entreprise et tous ceux qui cherchent à créer des quiz en ligne de manière sécurisée et efficace.
             """
             )
        st.write("[Learn More >](https://www.google.com)")

    # ---- WHAT I DO ----
    with st.container():
        st.write("---")
        left_column, right_column = st.columns(2)
        with left_column:
            st.header("Qu'est ce qu'on fait:")
            st.write("##")
            st.write(
                """
                Cette plateforme a été conçu pour:
                - presenter une solution complète de création de quiz en ligne avec une fonctionnalité de détection de tentatives de fraude.
                - création des quiz personnalisés pour une variété d'utilisations, notamment l'éducation, la formation en entreprise.
                - offrir une interface facile à utiliser pour la création de quiz avec des fonctionnalités personnalisables.
                - avoir à des rapports détaillés sur les tentatives de fraude détectées pour aider à maintenir l'intégrité des quiz."
                Cette plateforme a été conçu par des etudiants en master EID²
                """
            )
            st.write("[Learn More >](https://www.google.com/)")
        with right_column:
            st_lottie(lottie_coding, height=300, key="coding")

    
    # ---- CONTACT ----
    with st.container():
        st.write("---")
        st.header("Get In Touch With US!")
        st.write("##")

        # Documention: https://formsubmit.co/ !!! CHANGE EMAIL ADDRESS !!!
        contact_form = """
        <center>
        <form action="https://formsubmit.co/YOUR@MAIL.COM" method="POST">
            <input type="hidden" name="_captcha" value="false">
            <input type="text" name="name" placeholder="Your name" required>
            <input type="email" name="email" placeholder="Your email" required>
            <textarea name="message" placeholder="Your message here" required></textarea>
        </form>
        </center>
        """
        
        left_column, right_column = st.columns(2)
        with left_column:
            st.markdown(contact_form, unsafe_allow_html=True)
        with right_column:
            st.empty()



        def run_program():
            if st.button('Send'):
                subprocess.run(['python', 'example.py'])
        run_program()



if(file=="Create Quiz"):
    def main():
        st.title("Create a Simple Quiz")
        
        
        # Ask user for quiz title
        quiz_title = st.text_input("Enter quiz title:")
        
        title='./quiz/'+quiz_title+'.txt'

        # Ask user for quiz questions
        st.write("Enter quiz questions and answers:")
        num_questions = st.number_input("How many questions do you want to include?", min_value=1, step=1)
        questions = []
        for i in range(num_questions):
            question = {}
            question["question"] = st.text_input(f"Enter question {i+1}")
            question["options"] = st.text_input(f"Enter answer options for question {i+1} separated by commas (,)")
            question["answer"] = st.text_input(f"Enter the correct answer for question {i+1}")
            questions.append(question)
        

        butt=st.button("Save")
        # Save quiz to file
        if(butt):
            with open(title, "w") as f:
                #f.write(f"Quiz Title: {quiz_title}\n")
                for i, question in enumerate(questions):
                    f.write(f"{question['question']}\n")
                    options = question["options"].split(",")
                    for j, option in enumerate(options):
                        f.write(f"{chr(97+j)}. {option}\n")
                    f.write(f"{question['answer']}\n")

            st.write("Quiz saved to file.")
    main()

if(file=="Diagnostic"):

    st.sidebar.header('Quiz')
    file3 = st.sidebar.selectbox('', getAllFiles())
    st.sidebar.header('Eleve')
    file4 = st.sidebar.selectbox('',('Eleve 1',''))
    st.sidebar.header('Choix')
    file2 = st.sidebar.selectbox('',('Camera Frontale','Camera PC','Son','Gyroscope','Prediction'))

    if(file2=="Camera PC"):
        st.header('Camera PC')
        st.write("A travers ce graphique, nous pouvons visualiser les variations du champ de vision au fil du temps et ainsi mieux comprendre les changements qui se produisent dans notre environnement.")
        import pandas as pd

        # Read the data from the text file
        with open("log.txt", "r") as f:
            data = f.readlines()

        # Parse the data into a Pandas DataFrame
        df = pd.DataFrame([d.strip().split(" - ") for d in data], columns=["Time", "Number"])
        #df["Time"] = pd.to_datetime(df["Time"], format="%S")
        df["Time"] = pd.to_numeric(df["Time"])
        df["Number"] = pd.to_numeric(df["Number"].str.replace("Number: ", ""))

        # Plot a line chart of the number through the hours using Streamlit
        st.line_chart(df.set_index("Time")["Number"])
        st.area_chart(df.set_index("Time")["Number"])


    if(file2=="Gyroscope"):
        st.header('Gyroscope')
        st.write("Dans cette section, nous créons un graphique qui montre l'évolution des données issues du gyroscope. Ce graphique nous permet de suivre les variations des mesures du gyroscope dans le temps, ce qui peut être utile pour l'analyse de mouvements, la surveillance de la stabilité et la détection d'anomalies. En examinant les tendances et les modèles dans les données du gyroscope, nous pouvons obtenir des informations précieuses sur l'état et le comportement d'un système.")
        import pandas as pd

# Read the output.txt file and extract the x, y, and z values
        with open("output.txt", "r") as f:
            data = f.read().splitlines()

        values = []
        for line in data:
            # Extract the values of x, y, and z from each line
            x = float(line.split(",")[0].split("=")[1].strip())
            y = float(line.split(",")[1].split("=")[1].strip())
            z = float(line.split(",")[2].split("=")[1].strip())
            
            # Add the values to a list
            values.append([x, y, z])

        # Create a pandas DataFrame from the values list
        df = pd.DataFrame(values, columns=["x", "y", "z"])

        # Create a line chart to display the evolution of x, y, and z
        st.line_chart(df)

        # Create an area chart to display the evolution of x, y, and z
        st.area_chart(df)

    if(file2=="Camera Frontale"):
        
        st.header('Camera Frontale')
        st.write('On montre les images issues de la camera frontale reconnu par le modele de reconnaissance des images')

        # Set the path to the folder you want to check
        path = os.path.join(os.getcwd(), 'preuve/images')

        # Use the os module to count the number of files in the folder
        num_files = len(os.listdir(path))

        # Create a styled HTML message to display the number of files
        html = f"""
        <div style='background-color:#f0f0f0;padding:10px;border-radius:10px'>
            <h2 style='text-align:center'>There are {num_files} files in the folder</h2>
        </div>
        """

        # Display the message in the Streamlit app
        st.markdown(html, unsafe_allow_html=True)



        from PIL import Image

        # Set the path to the folder you want to display images from


        # Get a list of all image file names in the folder
        image_names = [f for f in os.listdir(path) if f.endswith('.jpg') or f.endswith('.jpeg') or f.endswith('.png')]

        # Loop through the list of image file names and display each image
        for image_name in image_names:
            image_path = os.path.join(path, image_name)
            image = Image.open(image_path)
            st.image(image, caption=image_name)


    if(file2=="Prediction"):
        st.header('Prediction')
        st.write("D'apres ce qu'on a obtenu des cateurs illustés dans les sous rubriques du diagnostique, on peut formuler la prediction suivante: la couleur orange du chart ci-dessus montre le pourcentage potentiel que le candidat a commis une fraude")

        valeur=0
        
        
        #Nombre d'image        
        path = os.path.join(os.getcwd(), 'preuve/images')
        num_files = len(os.listdir(path))

        if(num_files>5):
            valeur+=40
        else:
            valeur+=20
        
        
        #nombre de fois -4
        with open("log.txt", "r") as f:
            data = f.readlines()

        # Parse the data into a Pandas DataFrame
        df = pd.DataFrame([d.strip().split(" - ") for d in data], columns=["Time", "Number"])
        #df["Time"] = pd.to_datetime(df["Time"], format="%S")
        df["Time"] = pd.to_numeric(df["Time"])
        df["Number"] = pd.to_numeric(df["Number"].str.replace("Number: ", ""))

        counts = df['Number'].value_counts()

        freq_of_minus4 = counts[-4] / len(df)

        valeur+=int(freq_of_minus4/3)


        #Gyroscope
        with open("output.txt", "r") as f:
            data = f.read().splitlines()

        values = []
        for line in data:
            # Extract the values of x, y, and z from each line
            x = float(line.split(",")[0].split("=")[1].strip())
            y = float(line.split(",")[1].split("=")[1].strip())
            z = float(line.split(",")[2].split("=")[1].strip())
            
            # Add the values to a list
            values.append([x, y, z])

        # Create a pandas DataFrame from the values list
        df2 = pd.DataFrame(values, columns=["x", "y", "z"])




        diff_df = df2.diff()
        abs_diff_df = diff_df.abs()


        total_num_changes = ((abs_diff_df['x'] > 1) | (abs_diff_df['y'] > 1) | (abs_diff_df['z'] > 1)).sum()


        percent_changes = total_num_changes / len(df) * 100

        valeur+=percent_changes






        import plotly.graph_objs as go
        import random

        # Generate a random percentage between 0 and 100
        if(valeur>95):
            percentage = 95
        else:
            percentage=valeur

        # Define the data and layout for the Plotly pie chart
        data = [go.Pie(
                    values=[percentage, 100 - percentage],
                    labels=['Triche', ''],
                    hoverinfo='label+percent',
                    hole=0.8,
                    marker=dict(colors=['#FFC107', '#F5F5F5'], line=dict(color='#F5F5F5', width=2))
                )]
        layout = go.Layout(
                    autosize=True,
                    margin=dict(l=0, r=0, b=0, t=0),
                    showlegend=False,
                )

        # Display the Plotly chart in the Streamlit app
        st.plotly_chart(go.Figure(data=data, layout=layout))


    if(file2=="Son"):
        st.header('Son')
        from pydub import AudioSegment
        from pydub.playback import play

        # Define the folder where the .wav files are located
        folder_path = os.path.join(os.getcwd(), 'preuve/voices/')

        # Get a list of all the .wav files in the folder
        wav_files = [f for f in os.listdir(folder_path) if f.endswith('.wav')]

        # Display the list of .wav files in a dropdown menu
        selected_file = st.selectbox('Select a .wav file to play', wav_files)

        # Load the selected file and play it
        file_path = os.path.join(folder_path, selected_file)
        audio = AudioSegment.from_wav(file_path)
        st.audio(audio.raw_data, format='audio/wav')
        if st.button('Play'):
            play(audio)
