# -*- coding: utf-8 -*-
"""
Created on Sat May 25 15:22:41 2024

@author: Stéphane Pasquet
@url : https://www.mathweb.fr/euclide/quizmathweb/
"""



from tkinter import Label, Button, Tk, Frame, StringVar, OptionMenu, Text, END, Scrollbar, RIGHT, Y, LEFT, BOTH
from functools import partial
from sqlite3 import connect
from random import shuffle
from os import walk


class Quizz:
    def __init__(self, window , database):
        self.score = 0
        self.total = 0
        self.window = window
        window.title("Mathweb'Quizz - Version 0.1 (24/06/2020)")
        window.geometry('800x550')
        window.iconbitmap("quiz.ico")
        window.resizable(0,0)
        # interaction avec la base de données
        conn = connect(database)
        c = conn.cursor()
        self.liste_questions = [ ]
        c.execute("SELECT question,rep1,rep2,rep3,rep4,bonne_rep FROM questions")
        for row in c.fetchall():
            self.liste_questions += [ row ]
        c.close()
        shuffle(self.liste_questions)
        # question
        self.framequestion = Frame(window,bg='white',width='780', height='100')
        self.framequestion.grid_propagate(0)
        self.question = Text(self.framequestion, width=770, height=90, bg = 'white' )
        self.framequestion.place(x=10,y=10)
        self.question.place(x=0, y=0)
        # score
        self.framescore = Frame(window,bg='#c0c0c0',width='780', height='50')
        self.framescore.grid_propagate(0)
        self.scoreprint = Label(self.framescore, font=('Courrier', 25 , 'bold') , bg = '#c0c0c0' , fg = 'red')
        self.framescore.place(x=10,y=480)
        self.scoreprint.place(x=330, y=0)
        # propositions
        self.prop = [ None for i in range(4)]
        self.yposition = [ 120 , 210 , 300 , 390 ]
        for i in range(4):
            self.prop[i] = Button(window , width = 86 , height = 3 , font=('Courrier', 13) , bg = '#c0c0c0' )
            self.prop[i].place(x = 10 , y = self.yposition[i] )
        self.new_question()
        
    def new_question(self):
        self.total += 1
        quest = self.liste_questions.pop()
        self.question.delete(1.0,END)
        self.question.insert(END,quest[0])
        for i in range(0,4):
            self.prop[i].configure(text = quest[i+1] , bg = '#c0c0c0')
            self.prop[i].configure(command = partial(self.verif_answer,i,quest[5]-1))
                
    def verif_answer(self,current_prop,good_prop):
        temps = 1000
        if current_prop != good_prop:
            self.prop[current_prop].configure(bg = 'red')
            self.score -= 1
            temps = 5000
        self.prop[good_prop].configure(bg = 'green')
        self.score += 1
        self.scoreprint.configure(text = 'Score : ' + str(self.score) + ' / ' + str(self.total))
        if self.liste_questions:
            self.window.after(temps, self.new_question)
        else:
            self.end()
            
    def end(self):
        self.scoreprint.place(x=180, y=0)
        self.framescore.configure(bg = '#008a9c')
        self.scoreprint.configure(bg = '#008a9c' , fg = '#64c9e2')
        self.scoreprint.configure(text = 'Fin du quiz. Score final : ' + str(self.score) + ' / ' + str(self.total))

class Infos:
    def __init__(self , window):
        window.title("Informations")
        window.geometry('800x200')
        window.iconbitmap("quiz.ico")
        window.resizable(1,1)
        self.scrollbar = Scrollbar(window)
        self.scrollbar.pack( side = RIGHT, fill = Y )

        self.info = Text(window, bg = 'white' , yscrollcommand = self.scrollbar.set , width = '800')
        # ouverture du fichier "README.txt"
        with open("README.txt" , 'r' , encoding='utf-8') as f:
            for line in f:
                self.info.insert(END,line)
                
        self.info.pack( side = LEFT, fill = BOTH )
        self.scrollbar.config( command = self.info.yview )
        
def run_infos():
    window_info = Tk()
    Infos(window_info)
    window_info.mainloop()
        
if __name__ == '__main__':
    menu = Tk()
    menu.title("Mathweb'Quizz - Version 0.1 (24/06/2020)")
    menu.geometry('400x200')
    menu.iconbitmap("quiz.ico")
    menu.resizable(0,0)
    
    # liste des fichiers .db
    
    list_of_quiz = [ 'Choisissez un quiz' ]
    for root, dirs, files in walk("."):
        for name in files:
            if name.endswith('.db'):
                list_of_quiz += [ name.replace('.db','').replace('_',' ') ]
   

    name_quiz = StringVar(menu)
    name_quiz.set(list_of_quiz[0])
    Label(text = 'Veuillez choisir votre quiz :' , font = ('Helvetica', 12 )).pack()
    Label(text = '').pack()
    opt = OptionMenu(menu, name_quiz, *list_of_quiz[1:])
    opt.config(width=90, font=('Helvetica', 12))
    opt.pack(side='top')
    Label(text = '').pack()
    infos = Button(menu,text='Informations',command=run_infos)
    infos.pack()
        
    def callback(*args):
        if name_quiz.get() != 'Choisissez un quiz':
            window = Tk()
            Quizz(window , name_quiz.get().replace(' ','_') + '.db' )
            window.mainloop()
        
    name_quiz.trace("w", callback)
    menu.mainloop()