import requests
import streamlit as st
from streamlit_lottie import st_lottie
from PIL import Image
import subprocess
import os

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

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

# 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")


def run_program():
    cmds = [
    "python example.py",
    "python detect_sound.py",
    "python server3.py",
    "python serverTest.py"
    ]
    #procs = []
    #for cmd in cmds:
    #    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    #    procs.append(proc)
    processes = [subprocess.Popen(program, stdout=subprocess.PIPE, shell=True) for program in cmds]
    
    
    #for process in processes:
    #    st.text(f"Output of {process.args}:")
    #    while True:
    #        output = process.stdout.readline().decode().strip()
    #        if not output:
    #            break
    #        st.text(output)
    
    #subprocess.run(['python','face_detection.py'])
    #subprocess.run(['python','detect_sound.py'])
    #subprocess.run(['python','gyro.py'])
    #subprocess.run(['python','serverTest.py'])


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','Quiz'))
#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 Etudiant")
        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()





if(file=="Quiz"):

    file2 = st.sidebar.selectbox('', getAllFiles())
    #q=st.sidebar.button('OK')


    #if(st.button('Check user')):
    #    run_program()
    #if(q):
    run_program()
    with open(os.path.join(dir, file2), "r") as file:
                lines = file.readlines()

            # Parse the quiz questions and answers
    questions = []
    for i in range(0, len(lines), 6):
                question = lines[i].strip()
                choices = [choice.strip() for choice in lines[i+1:i+5]]
                answer = lines[i+5].strip()
                questions.append({"question": question, "choices": choices, "answer": answer})

            # Initialize the quiz score and current question index
    score = 0
    current_question = 0

            # Display each quiz question and answer choices
    while current_question < len(questions):
                st.write(f"Question {current_question+1}: {questions[current_question]['question']}")
                #for i, choice in enumerate(questions[current_question]['choices']):
                #    st.write(f"{i+1}. {choice}")
                # Allow the user to select an answer choice
                selected_choice = st.radio("Select your answer:", options=questions[current_question]['choices'])
                # Check if the user's answer is correct
                
                #if selected_choice == questions[current_question]['answer']:
                #    st.write("Correct!")
                #    score += 1
                #else:
                #    st.write(f"Wrong! The correct answer is {questions[current_question]['answer']}.")
                
                current_question += 1

            # Display the final quiz score
            #st.write(f"Your final score is {score}/{len(questions)}")
    checkbox = st.checkbox("Je confirme mes reponses")
    #if(checkbox):
    b=st.button('Send')
    if(b and checkbox):
        
        st.write("Reponses envoyées avec succes")
        
