import kivy
import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput

class Etudiant(App):
# layout
    def build(self):
        layout = BoxLayout(padding=5, orientation='vertical')
        recherchemodule = GridLayout(cols=2, rows=10)
        resultat = BoxLayout()
        btn = Button(text="OK", size_hint_x=None, width=250)
        btn.bind(on_press=self.buttonClicked)
        self.input = TextInput(text='Looking for a student?', multiline=False, font_size=20)
        self.output = TextInput(text='Output will be here !', font_size=20)
        self.input.bind(on_text_validate=self.on_enter)
        recherchemodule.add_widget(self.input)
        recherchemodule.add_widget(btn)
        resultat.add_widget(self.output)
        layout.add_widget(recherchemodule)
        layout.add_widget(resultat)

        dictionnaire = {}
        file = open("./nommatiers.csv", mode='r')
        for (nom, note, matiere) in [l.split(';') for l in file.readlines()[1:]]:
            if nom not in dictionnaire.keys():
                dictionnaire[nom] = {matiere:float(note)}
            else :
                dictionnaire[nom][matiere] = float(note)
        self.content = dictionnaire
        return layout

# functions
    def buttonClicked(self,btn):
        nom = self.input.text.upper()
        self.output.text = str(self.content[nom])
        todisplay = [key[:-1]+'('+str(value)+')' for key, value in self.content[nom].items()]
        self.output.text = nom[0].upper()+nom[1:].lower()+" a les notes suivantes : "+', '.join(todisplay)

    def on_enter(self, input):
        nom = self.input.text.upper()
        todisplay = [key[:-1]+'('+str(value)+')' for key, value in self.content[nom].items()]
        self.output.text = nom[0].upper()+nom[1:].lower()+" a les notes suivantes : "+', '.join(todisplay)

# run app
if __name__ == "__main__":
    Etudiant().run()
