import os
import sys
import sys
import sqlite3
import community as community_louvain
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import networkx as nx
import tkinter.messagebox as messagebox
import tkinter.messagebox as tkMessageBox
from PIL import Image, ImageTk
import time
root.title("Connexion  système")
width = 430
height = 276
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
root.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
localtime=time.asctime(time.localtime(time.time()))
#menu frame
menu = Menu(root)
root.config(menu=menu)
#menu1
home = Menu(menu)
menu.add_cascade(label='Aide',menu=home)
#menu2
home2 = Menu(menu)
menu.add_cascade(label='Info',menu=home2)
#menu3
home3 = Menu(menu)
menu.add_cascade(label='Terms utilisations',menu=home3)
#menu4
home4 = Menu(menu)
menu.add_cascade(label='Options',menu=home4)
#menu4
home5 = Menu(menu)
menu.add_cascade(label='File',menu=home5)
#=======================================VARIABLES=====================================
USERNAME = StringVar()
PASSWORD = StringVar()
FIRSTNAME = StringVar()
LASTNAME = StringVar()
N = IntVar()
M = IntVar()
explanation = """At present, only GIF and PPM/PGM
formats are supported, but an interface 
exists to allow additional image file
formats to be added easily."""
#Button functions
def remarques():
     os.system('python remarques.py')
def Catalogue() :
     messagebox.showinfo("success message", "Catalogue")
def Chercheurs():
    os.system('python chercheurs.py')
def Editorimg() :
    os.system('python editor.py')
def Développeurs() :
    os.system('python Register.py')
def Employeurs():
    os.system('python part_manager.py')
def Generate():
     messagebox.showinfo("success message", "the process of genetaring graph succesed")
def Detecte():
     messagebox.showinfo("success message", "the process of detecting graph is succesed")
def Exitlouvain():
    Home.destroy()
def Virtualise():
    f1.selection_clear()
    photo= PhotoImage(file = r"Graph.png")
           #this new image is 3x the original  
    photograph2= photo.subsample(2, 2)
    Label(f1, image = photograph2,
                    compound = LEFT).pack(side = RIGHT)
    messagebox.showinfo("Succès", "l'opération de détection success!")
    f1.mainloop()
def Virtualise2():
    f2.selection_clear()
    photo= PhotoImage(file = r"Graph2.png")
           #this new image is 3x the original  
    photograph2= photo.subsample(2, 2)
    Label(f2, image = photograph2,
                    compound = LEFT).pack(side = RIGHT)
    messagebox.showinfo("success message", "Girvan new man détetcion!")
    f2.mainloop()
#==============================FRAMES=========================================
Top = Frame(root, bd=2,  relief=RIDGE)
Top.pack(side=TOP, fill=X)
Form = Frame(root, height=200)
Form.pack(side=TOP, pady=20)
#==============================LABELS=========================================
lbl_title = Label(Top, text = "Communauté détection système",font=('arial', 11),fg="white")
lbl_title.pack(fill=X)
lbl_username = Label(Form, text = "Nom:", font=('arial', 11), bd=14)
lbl_username.grid(row=0, sticky="e")
lbl_password = Label(Form, text = "Mot de passe:", font=('arial', 11), bd=14)
lbl_password.grid(row=1, sticky="e")
lbl_text = Label(Form)
lbl_text.grid(row=2, columnspan=2)
lbl_Register = Label(Form, text = "Enregistrer",font=('arial', 8), bd=14)
lbl_Register.configure(background='black')
lbl_title.configure(background='black')
root.configure(background='Lightgrey')
lbl_username.configure(background='Lightgrey')
lbl_password.configure(background='Lightgrey')
Form.configure(background='Lightgrey')
#==============================ENTRY WIDGETS==================================
username = Entry(Form, textvariable=USERNAME, font=(6))
username.grid(row=0, column=1)
password = Entry(Form, textvariable=PASSWORD, show="*", font=(6))
password.grid(row=1, column=1)
#==============================
def Database():
    global conn, cursor
    conn = sqlite3.connect("pythontut.db")
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY  AUTOINCREMENT, username TEXT, password TEXT)")       
    cursor.execute("SELECT * FROM `member` WHERE `username` = 'admin' AND `password` = 'admin'")
    if cursor.fetchone() is None:
        cursor.execute("INSERT INTO `member` (username, password) VALUES('admin', 'admin')")
        conn.commit()
#==============================METHODS========================================
def Login():
    Database()
    if USERNAME.get() == "" or PASSWORD.get() == "":
        lbl_text.config(text="Veuillez remplir le champ requis!", fg="red")
    else:
        cursor.execute("SELECT * FROM `member` WHERE `username` = ? AND `password` = ?", (USERNAME.get(), PASSWORD.get()))
        if cursor.fetchone() is not None:
            HomeWindow()
            USERNAME.set("")
            PASSWORD.set("")
            lbl_text.config(text="")
        else:
            lbl_text.config(text="Mot de pass incorrect ou invalid", fg="red",background='lightgrey')
            USERNAME.set("")
            PASSWORD.set("")
    cursor.close()
    conn.close()
    lbl_text.configure(background='lightgrey')
def Next2():
    global f2
    Home2 = Toplevel()
    Home2.title("Application détection de communauté")
    Home2.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    width = 770
    height = 620
    Home2.configure(background="black")
    Home2.geometry("%dx%d+%d+%d" % (width, height, x, y))
    lbl_home2 = Label(Home2, text="BIENVENUE DANS LE SYSTEME D'ALGORITHME!",fg="white",background='black',font=('Times' ,15, 'italic')).pack()
    Home.configure(background='black')
    lbl8=Label(Home2, text="APPLICATIONS DES ALGORITHMES SUR LES MODELES", fg='red', font=("Helvetica", 16))
    lbl8.place(x=60, y=50)
    lbl8.configure(background='black')
    lbl_vertix2.configure(background='black')

    photo= PhotoImage(file = r"icons\algorithme.png")
   #this new image is 3x the original  
    photoGirven= photo.subsample(2, 2)
    btnewman=Button(Home2,compound = LEFT, 
    image=photoGirven, text="Girvan-newman", fg='white',command=run3)
    btnewman.place(x=80, y=100)
    btnewman.configure(background='black')
    photo= PhotoImage(file = r"icons\Exit2.png")
    photoexit2=photo.subsample(2,2)
    exit_actions2 = Button(Home2,compound = LEFT, 
    image=photoexit2,text='Exit',bg="powder blue",font=("arial",9),command=Exitlouvain)

    lbledges2 = Label(Home2, text = "Edges values:(ni)", font=('arial', 11), bd=14,bg="lightgrey")
    lbledges2.place(x=80, y=330)
    lblvertex2 = Label(Home2, text = "Virtex values:(mi)", font=('arial', 11), bd=14,bg="lightgrey")
    lblvertex2.place(x=80, y=390)
    txtfld5=Entry(Home2, text="This is Entry Widget3", bd=4)
    txtfld5.place(x=80, y=370)
    txtfld7=Entry(Home2, text="This is Entry Widget4", bd=4)
    txtfld7.place(x=80, y=430)
    
    photo= PhotoImage(file = r"icons\Back.png")
    Back2=photo.subsample(2,2)
    btn_backG= Button(Home2,compound = LEFT, 
    image=Back2,text='Back', command=Back1,background='white',fg='black')
    btn_backG.place(x=180, y=550)
    
    exit_actions2.place(x=590,y=570)



    #pictures
    photo= PhotoImage(file = r"icons\takenotes2.png")
   #this new image is 3x the original  
    photonotes5= photo.subsample(2, 2)  
    btn_addnote2= Button(Home2,compound = LEFT, 
    image=photonotes5 ,text='Ajouté remarques',command=Generate,fg='white',bg="blackg")
    btn_addnote2.place(x=405, y=470)




       #Genrate button
    photo= PhotoImage(file = r"icons\Generate.png")
    photogeneratek=photo.subsample(2,2)
    btn_generatek= Button(Home2,compound = LEFT, 
    image=photogeneratek,text='Generate',command=Generate,fg='black')
    btn_generatek.place(x=80, y=460)
    #Detect button

    photo= PhotoImage(file = r"icons\vertualise.png")
   #this new image is 3x the original  
    photovert2= photo.subsample(2, 2)


    
    btn_virtualise2= Button(Home2,compound = LEFT, 
    image=photovert2,text='Virtualise',command=Virtualise2,fg='black')
    btn_virtualise2.place(x=563, y=470)
    btn_virtualise2.configure(background='black')
    
    photo= PhotoImage(file = r"icons\Insertpicture.png")
    photoinsertpicture2=photo.subsample(2,2)
    btn_editimage2= Button(Home2,compound = LEFT, 
    image=photoinsertpicture2,text='Edit Image',command=Editorimg,fg='white')
    btn_editimage2.place(x=480, y=470)
    btn_editimage2.configure(background='black')

    #print Button
    photo= PhotoImage(file = r"icons\printer.png")
   #this new image is 3x the original  
    photo_printer2= photo.subsample(2, 2)  
    btn_printer2= Button(Home2,compound = LEFT, 
    image=photo_printer2,text='PrintGraph',command=Generate,fg='white')
    btn_printer2.place(x=635, y=470)
    btn_printer2.configure(background='black')

    Home2.mainloop()
def HomeWindow(): 
    global Home ,Home2,Louvain1,Home5,f1,f2  
    root.withdraw()  
    Home = Toplevel()
    Home2 = Toplevel()
    Home.title("Application détetction de communauté système")
    Home2.title("Application detecting community")
    Home.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    Home.configure(background='lightgrey')
    Home2.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    width = 370
    height = 220
    photo= PhotoImage(file = r"icons\Exit2.png")
    photoexit1=photo.subsample(2,2)
    exit_actions = Button(Home,compound = LEFT, 
    image=photoexit1,text='Fermer',bg="lightgrey",font=("arial",9),command=Exitlouvain)
    exit_actions.place(x=190,y=140)
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.resizable(0, 0)
    Home.geometry("%dx%d+%d+%d" % (width, height, x, y))
    lbl_home = Label(Home, text="BIENVENUE DANS LE SYSTEME D'ALGORITHME!",fg="white",background='black',font=('Times' ,10, 'italic')).pack()
    Home.configure(background='black')
    Home2.geometry("%dx%d+%d+%d" % (width, height, x, y))
   #this new image is 3x the original  
    photovert= photo.subsample(2, 2)
    my_menu= Menu(root)
    root.config()
    photo= PhotoImage(file = r"icons\algorithme.png")
   #this new image is 3x the original  
    photolouvain= photo.subsample(2, 2)
    
    btna1=Button(Home,compound = LEFT, 
    image=photolouvain,text="Louvain", fg='white',command=run)
    btna1.place(x=80, y=100)
    btna=Button(Home,compound = LEFT, 
    image=photolouvain,text="Girvan-newman", fg='white',command=run3)
    btna.place(x=160, y=100)
    btna.configure(background='black')
    btna1.configure(background='black')
    btnewman=Button(Home2, text="Girvan-newman", fg='white',command=run3)
    btnewman.place(x=80, y=100)
    btnewman.configure(background='black')
    lbl8=Label(Home2, text="Algorithm 02 :Girvan-newman", fg='red', font=("Helvetica", 16))
    lbl8.place(x=60, y=50)
    lbl8.configure(background='lightgrey')
    photo= PhotoImage(file = r"icons\Back.png")
    Back=photo.subsample(2,2)
    btn_back= Button(Home,compound = LEFT, 
    image=Back,text='Précident', command=Back1,background='white',fg='black')
    btn_back.place(x=180, y=550)

    photo= PhotoImage(file = r"icons\Next.png")
    Next=photo.subsample(2,2)
    
    btn_back= Button(Home,compound = RIGHT, 
    image=Next,text='Suivant', command=Next2,background='white',fg='black')
    btn_back.place(x=480, y=550)
#Exit button


        
    lbledgesb = Label(Home2, text = "Edges values:(lower than n)", font=('arial', 11), bd=14)
    lbledgesb.place(x=80, y=330)
    lblvertexb = Label(Home2, text = "Virtex values:(lower than m)", font=('arial', 11), bd=14)
    lblvertexb.place(x=80, y=390)
    txtfld3b=Entry(Home2, text="This is Entry Widget3", bd=4)
    txtfld3b.place(x=80, y=370)
    txtfld4b=Entry(Home2, text="This is Entry Widget4", bd=4)
    txtfld4b.place(x=80, y=430)
    lbledgesb.configure(background='lightgrey')
    lblvertexb.configure(background='lightgrey')

    btn_backb= Button(Home2, text='Back', command=Back,background='blue',fg='white')
    btn_backb.place(x=180, y=550)
    btn_next= Button(Home2, text='Next', command=Next2,background='blue',fg='white')
    btn_next.place(x=480, y=550)

    btn_generate2= Button(Home2, text='Generate',command='Generate',fg='black')
    btn_generate2.place(x=80, y=460)
    btn_detect2= Button(Home2, text='Detect',command='Detect',fg='black')
    btn_detect2.place(x=180, y=460)
    btn_editimage2= Button(Home2, text='Edit Image',command='Edit Image',fg='black')
    btn_editimage2.place(x=480, y=500)
    
  
    btn_editimage2.configure(background='black')
    btn_generate2.configure(background='lightcoral')
    btn_detect2.configure(background='lightcoral')
    Home2.destroy()

    #menu simple
    menu = Menu(Home)
    Home.config(menu=menu)
    home=Menu(menu)
    menu.add_cascade(label='Accueille',menu=home)
    home.add_command(label='Take a Tour!!',command=taketour)
    home.add_command(label='conditions utilisations',command=terms_of_use)
    home.add_separator()
    menu.add_cascade(label='Aide',menu=Home)
    exit_button=Menu(menu)
    menu.add_cascade(label='Fermer',menu=exit_button)
    exit_button.add_command(label='Fermer',command=Home.destroy)

    #insert pictures of graph
    photo = PhotoImage(r'file=C:\Users\belha\Desktop\projet\louvain.png')
    Lower_frame=Frame(Home)
    label = Label(Lower_frame, image=photo)
    label.pack()
    Home.mainloop()
def taketour():
    os.system('python Community_detection.py')
def terms_of_use():
    print("terms of use ")

def Back1():
    Home.destroy()
    root.deiconify()
def Back4():
    Home.deiconify()
    Home4.destroy()
def run():
    root.withdraw()
    global Home4
    Home4 = Toplevel()
    Home4.title("Louvain avec les modèles")
    Home4.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    lbl_home4 = Label(Home4, text="Bienvenue ,système modèles choix!",background='black',font=('Times' ,11, 'bold italic'),fg='white').pack()
    Home4.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    lblrun=Label(Home4, text="APPLICATION LOUVAIN AVEC :", fg='white', font=("arial", "13"))
    lblrun.configure(background='black')
    lblrun.place(x=35, y=45)
    width = 400
    height = 300
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width/2) - (width/2) 
    y = (screen_height/2) - (height/2)
    root.resizable(0, 0)
    Home4.geometry("%dx%d+%d+%d" % (width, height, x, y))
    Home4.configure(background='black')
    btn_louvain1= Button(Home4, text='KARATE CLUB',command=louvain1,fg='white',bg='black')
    btn_louvain1.place(x=70, y=120)
    btn_louvain2= Button(Home4, text='BARBELL',command=louvain2,fg='white',bg='black')
    btn_louvain2.place(x=180, y=120)
    btn_louvain1.configure(background='black')
    btn_louvain2.configure(background='black')
    exit_button8 = Button(Home4,text='Fermer',font=("arial",9),command=Home4.destroy)
    exit_button8.place(x=350,y=220)
    btn_editimage4= Button(Home4, text='Editer Image',command=Editorimg,fg='black')
    btn_editimage4.place(x=300, y=120)
    btn_editimage4.configure(background='white')

    photo= PhotoImage(file = r"icons\Back.png")
    Back=photo.subsample(2,2)
    btn_backb= Button(Home4,compound = LEFT, 
    image=Back,text='Précédent', command=Back4,background='white',fg='black')
    btn_backb.place(x=40, y=220)
    menu = Menu(Home4)
    Home4.config(menu=menu)
    home=Menu(menu)
    menu.add_cascade(label='Home',menu=home)
    home.add_command(label='Take a Tour!!',command=taketour)
    home.add_separator()
    exit_button=Menu(menu)
    menu.add_cascade(label='Exit',menu=exit_button)
    exit_button.add_command(label='Exit',command=Exit)    
    Home4.mainloop()
def run3():
    root.withdraw()  
    Home3 = Toplevel()
    Home3.title("Application détection de commaunté")
    Home3.configure(background='black')
    #Choice Algorithme
    lbl_home3 = Label(Home3, text="Modèles choix!",background='black',font=('arial', 11,'bold'),fg='white').pack()
    Home3.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    lbl=Label(Home3, text="APPLICATIONS DES ALGORITHMES SUR LES MODELES", fg='white', font=("arial", "11"))
    lbl.place(x=35, y=45)
    lbl.configure(background='black')
    width = 320
    height = 250
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.resizable(0, 0)
    Home3.geometry("%dx%d+%d+%d" % (width, height, x, y))
    Home3.configure(background='Lightgrey')
    exit_button6 = Button(Home3,text='Fermer',font=("arial",9),command=Home3.destroy)
    exit_button6.place(x=350,y=220)
    btn_Girvan1= Button(Home3, text='KARATE MODEL',command=run7,fg='white')
    btn_Girvan1.place(x=70, y=120)
    btn_Girvan2= Button(Home3, text='BARBALL MODEL',command=run8,fg='white')
    btn_Girvan2.place(x=190, y=120)
    btn_Girvan1.configure(background='black')
    btn_Girvan2.configure(background='black')
    btn_backb= Button(Home3, text='précédent', command=Back1,background='white',fg='black')
    btn_backb.place(x=40, y=220)
#==============================BUTTON louvain=================================
#==============================Pictures declaration===========================
global img
def louvain1():
    os.system('python louvain.py')
def louvain2():
    os.system('python louvain2.py')
def run7():
    os.system('python Girvan-newman.py')
def run8():
    os.system('python Girvan-newman2.py')
def Louvain():
    Home.destroy()
    root.deiconify()
def Register():
    os.system('python Register.py')
def Register1():
    root2 = Tk()
    root2.geometry("340x300+0+0")
    root2.title("Choix d'utilisateurs système")
    root2.wm_iconbitmap(r'C:\Users\belha\Desktop\projet\system.ico')
    Tops2 = Frame(root2,bg="Black",width = 450,height=50,relief=SUNKEN)
    Tops2.pack(side=TOP)
    lblinfo2 = Label(Tops2, font=("Times", "12", "bold italic" ),text="choix d'utilisateurs",fg="white",bd=10,anchor='w')
    lblinfo2.grid(row=0,column=0)
    lblinfo2.configure(background='black')
    lblinfo2 = Label(Tops2, font=( 'arial' ,11, ),text=localtime,fg="white",anchor=W)
    lblinfo2.grid(row=1,column=0)
    lblinfo2.configure(background='black')
    root2.configure(background='black')
    exit_button2 = Button(root2,text='Fermer',font=("arial",9),bg="white",fg="black",command=root2.destroy)
    exit_button2.place(x=250,y=200)
    lblicopyrigth2 = Label(root2, font=( "Times", "8", "bold italic"),text="tout droit réserver 2021",fg="white",bd=10,anchor='w')
    lblicopyrigth2.place(x=120, y=200)
    lblicopyrigth2.configure(background='black')
    #menu
    menu = Menu(root2)
    root2.config(menu=menu)
    #menu1
    home = Menu(menu)
    menu.add_cascade(label='Help',menu=home)
    home.add_command(label='Users guide',command=Catalogue)
    #menu2
    home2 = Menu(menu)
    menu.add_cascade(label='Info',menu=home2)
    #menu3
    home3 = Menu(menu)
    menu.add_cascade(label='Terms of use',menu=home3)
    home.add_command(label='Users guide',command=Catalogue)
    #menu4
    home4 = Menu(menu)
    menu.add_cascade(label='Options',menu=home4)
    home4.add_command(label='EditeurImage',command=Catalogue)
    #menu5
    home5 = Menu(menu)
    menu.add_cascade(label='About us',menu=home5)
    home5.add_command(label='Master ISI',command=Catalogue)
    #BUTTON USERS
    f2 = Frame(root2,width = 450,height=300,relief=SUNKEN)
    f2.pack(side=TOP)
    f2.configure(background='lightgrey')
    #button pictures

  
   
    btnexita=Button(f2,padx=16,pady=8,font=('arial' ,8,'bold'),width=8, text="CHERCHEURS",  bg="lightgrey",fg="black",command=Chercheurs)
    btnexita.grid(row=1, column=2)

    btnexitb=Button(f2,padx=16,pady=8,font=('arial' ,8,'bold'),width=8, text="EMPLOYEURS",  bg="lightgrey",fg="black",command=Employeurs)
    btnexitb.grid(row=2, column=2)
  
    btnexitc=Button(f2,padx=16,pady=8,font=('arial' ,8,'bold'),width=8, text="DEVELOPPEURS", bg="lightgrey",fg="black",command=Développeurs)
    btnexitc.grid(row=3, column=2)
    root2.mainloop()
    f2.mainloop()
def Back3():
    Home5.destroy()
    root.deiconify()
def run11():
    os.system('python Register.py')
#==============================BUTTON WIDGETS=================================
btn_login = Button(Form, text="Connexion", width=40, command=Login)
btn_login.grid(pady=25, row=3, columnspan=2)
btn_login.bind('<Return>', Login)
btn_login.configure(background='black',fg='white')
btn_Register= Button(Form, text='Inscrire',fg='white',command=Register1,width=10)
btn_Register.configure(background='black',fg='white')
btn_Register.place(x=230, y=168)
#==============================Register=================================
def Login():
    Database()
    if USERNAME.get == "" or PASSWORD.get() == "":
        lbl_result1.config(text="Please complete the required field!", fg="orange")
    else:
        cursor.execute("SELECT * FROM `member` WHERE `username` = ? and `password` = ?", (USERNAME.get(), PASSWORD.get()))
        if cursor.fetchone() is not None:
            lbl_result1.config(text="You Successfully Login", fg="blue")
        else:
            lbl_result1.config(text="Invalid Username or password", fg="red")

#==============================Store the values=================================
def retrieve_input():
    eq_input = N.get()
    return eq_input
def Exit():
    result = tkMessageBox.askquestion('Système','Êtes-vous sûr de vouloir quitter ?', icon="warning")
    if result == 'yes':
        root.destroy()
        exit()
#==============================Graph function=================================
menu = Menu(root)
root.config(menu=menu)
home=Menu(menu)
menu.add_cascade(label='Accueille',menu=home)
home.add_command(label='Take a Tour!!',command=taketour)
home.add_separator()
exit_button=Menu(menu)
menu.add_cascade(label='Fermer',menu=exit_button)
exit_button.add_command(label='info',command=Exit)        
#==============================METHODS========================================
if __name__ == '__main__':
    root.mainloop()