# Th krebs, le 13/01/2014
# -*-coding:utf-8 -*-
#---------------importation des bibliothèques-------------------
from __future__ import division
from lycee import *
from tkinter import *
import sqlite3
import os
import os.path
from os import chdir

#---------------récupération répertoire de travail--------------
rep = os.getcwd()
print(rep)
#--------------création répertoire sqlite3----------------------
try:
    os.mkdir(rep + "/Sqlite3")
except:
    print("\Sqlite3 existe déjà")
rep=rep+"\Sqlite3"
print(rep)
os.chdir(rep)
#-----------création et connexion à la base de données----------
fichierDonnees =rep+"/repertoire.sq3"
#print(fichierDonnees)
con=sqlite3.connect(fichierDonnees)
try:
    con.execute("CREATE TABLE membres (prenom TEXT, nom TEXT, numero INTEGER)")
except:
    print("la table est déjà crée")
#---------------------------------------------définition des fonctions------------------------------------------------
def repondre(titre,parent,boutton):
    Fenetre = Tk()
    Fenetre.title(titre)
    Fenetre.configure(bg='grey')
    Fenetre.tk_focusFollowsMouse()
    nom = Label(Fenetre, text = parent, bg='grey')
    reponse=StringVar()
    lareponse = Entry(textvariable=reponse, bd=5,background='white',relief='sunken', width=50)
    valeur = Button(Fenetre, text = boutton,bg='grey',justify='left', command=Fenetre.quit)
    affichage = Label(Fenetre,bg='grey', width=50)
    nom.pack()
    lareponse.pack()
    valeur.pack()
    affichage.pack()
    Fenetre.mainloop()
    saisir=lareponse.get()
    Fenetre.destroy()
    return (saisir)

def afficher(nblignes,titre,parent,boutton):
    Fenetre = Tk()
    Fenetre.title(titre)
    Fenetre.configure(bg='grey')
    Fenetre.tk_focusFollowsMouse()
    nom=nblignes*[""]
    for i in range(0,nblignes):
        nom[i] = Label(Fenetre, text = parent[i], bg='grey')
        nom[i].pack()
        trait=Label(Fenetre, text = '_________________________________________________________________________', bg='grey')
        trait.pack()
    valeur = Button(Fenetre, text = boutton,bg='grey',justify='left', command=Fenetre.quit)
    affichage = Label(Fenetre,bg='grey', width=50)

    valeur.pack()
    affichage.pack()
    Fenetre.mainloop()
    Fenetre.destroy()
    return ()

def enreg():
    fiche=3*['']
    fiche=GestionNouvContact()
    con.execute("insert into membres (prenom, nom, numero) values (?,?,?)",fiche)
    con.commit()
    return()

def GestionNouvContact():
        Fenetre = Tk()
        Fenetre.title("nouveau contact")
        Fenetre.configure(bg='grey')
        Fenetre.tk_focusFollowsMouse()
        igt=0
        nomchp=['prenom','nom','numéro de mobile']
        labelchp = 3*['']
        reg = 3*['']
        registred = 3*['']
        saisi = 3*['']
        for igt in range(0,(3)):
            labelchp[igt] = Label(Fenetre, text = nomchp[igt], bg='grey')
            reg[igt]=StringVar()
            registred[igt] = Entry(textvariable=reg[igt], bd=5,background='white',relief='sunken', width=50)
            labelchp[igt].pack()
            registred[igt].pack()
        valeur = Button(Fenetre, text = "Valider",bg='grey',justify='left', command=Fenetre.quit)
        affichage = Label(Fenetre,bg='grey', width=50)
        valeur.pack()
        affichage.pack()
        Fenetre.mainloop()
        for igt in range(0,3):
            saisi[igt]=registred[igt].get()
        Fenetre.destroy()
        return saisi

def ShowChoice():
        mod=v.get()
        return mod

def Recherche():
        recherche=repondre('recherche','nom','suivant')
        t=(recherche,)
        index=0
        affprenom=[""]
        affnom=[""]
        affnumero=[""]
        cursor = con.execute("SELECT * FROM membres WHERE nom=? order by nom , prenom",t)
        for j in cursor:
            index=index+1
        fiches=(index+1)*[""]
        k=0
        cursor = con.execute("SELECT * FROM membres WHERE nom=? order by nom , prenom",t)
        for row in cursor:
           affprenom="Prenom: "+str(row[0])
           affnom="Nom: "+str(row[1])
           affnumero="Numero: "+str(row[2])
           fiches[k]=affprenom+"  |  "+affnom+"  |  "+affnumero+"  |  "
           k=k+1
        return(index,fiches)

#-------------------------------------------------------programme principal------------------------------------------------------
#----------initialisation menu------------
root = Tk()
v = IntVar()
v.set(1)
boutton='suivant'
mode = [
               ("enregistrer contact",1),
               ("lister contacts",2),
               ("rechercher contact",3),
               ("effacer contact",4),
               ("mettre à jour contact",5),
               ("quitter",6)
               ]
#----------appel du menu----------
Label(root,text="""action à effectuer:""",justify = LEFT,padx = 20).pack()
for txt, val in mode:
    Radiobutton(root,text=txt,indicatoron = 0,width = 20,padx = 20,variable=v,command=ShowChoice,value=val).pack(anchor=W)
Button(root, text = boutton, command=root.quit).pack()
root.mainloop()
root.destroy()
mod=ShowChoice()

while (mod != 6):
    mod=ShowChoice()

#----------Gestion du mode enregistrement----------
    if mod == 1:
        enreg()

#----------Gestion du mode lister----------
    if mod == 2:
        index=0

        affprenom=[""]
        affnom=[""]
        affnumero=[""]
        cursor = con.execute("select prenom, nom, numero  from membres")
        for j in cursor:
            index=index+1
        fiches=(index+1)*[""]
        k=0
        cursor = con.execute("select prenom, nom, numero  from membres order by nom , prenom")
        for row in cursor:
           affprenom="Prenom: "+str(row[0])
           affnom="Nom: "+str(row[1])
           affnumero="Numero: "+str(row[2])
           fiches[k]=affprenom+"  |  "+affnom+"  |  "+affnumero+"  |  "
           k=k+1
        afficher(index,'Liste des contacts',fiches,'suivant')

#----------Gestion Recherche-----------------
    if mod == 3:
        [index,fiches]=Recherche()
        afficher(index,'Résultat de la recherche',fiches,'suivant')

#----------Gestion effacement-----------------
    if mod == 4:
        [index,fiches]=Recherche()
        afficher(index,'Recherche nom contact à effacer',fiches,'suivant')
        effacer=repondre('effacement','nom contact à effacer','recherche')
        effacer2=repondre('effacement','prénom contact à effacer','recherche')
        eff=[""]
        eff[0]=effacer2+" "+effacer
        t=(effacer,effacer2,)
        cursor = con.execute("DELETE FROM membres WHERE nom=? and prenom=?",t)
        con.commit()
        afficher(1,'Contact éffacé: ',eff,'suivant')

#----------Gestion mise à jour-----------------
    if mod == 5:
        [index,fiches]=Recherche()
        afficher(index,'Recherche nom contact à mettre à jour',fiches,'suivant')
        actu=repondre('Mise à jour','nom contact à mettre à jour','recherche')
        actu2=repondre('Mise à jour','prénom contact à mettre à jour','recherche')
        t=(actu,actu2,)
        cursor = con.execute("SELECT * FROM membres WHERE nom=? and prenom=?",t)
        for row in cursor:
           numero='ancien numéro: '+str(row[2])
        maj=repondre('nouveau numero',numero,'mise à jour')
        nvnum=[""]
        nvnum[0]=actu2+" "+actu+" "+str(maj)
        r=(maj,actu,actu2)
        cursor = con.execute("UPDATE membres SET numero=? WHERE nom=? and prenom=?",r)
        con.commit()
        afficher(1,'Contact mis à jour: ',nvnum,'suivant')

#----------menu boucle------------
    root = Tk()
    v = IntVar()
    v.set(1)  # initializing the choice, i.e. Python
    boutton='suivant'
    mode = [
                   ("enregistrer contact",1),
                   ("lister contacts",2),
                   ("rechercher contact",3),
                   ("effacer contact",4),
                   ("mettre à jour contact",5),
                   ("quitter",6)
                   ]
    Label(root,text="""action à effectuer:""",justify = LEFT,padx = 20).pack()
    for txt, val in mode:
        Radiobutton(root,text=txt,indicatoron = 0,width = 20,padx = 20,variable=v,command=ShowChoice,value=val).pack(anchor=W)
    Button(root, text = boutton, command=root.quit).pack()
    root.mainloop()
    root.destroy()
    mod=ShowChoice()
con.commit()
con.close()

#-----------------------------------------fin du programme principal-----------------------------------------