# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 14:46:47 2021

@author: G5A
"""

import tkinter as tk
import functions as fn



def valider_cle(code, key):
    """check si type de cle correspond au type de code (int->cesar || string->wegner)"""
    if(code == "Wegner" and not any(map(str.isdigit, key))):
        return True
    elif(code == "Cesar" and key.isdigit()):
        return True
    elif code=="RC4":
        return True
    elif(code == "Affine" and affine_keys_valid(key)):
        return True
    print("valider_cle bugg not valid")
    return False
        


#=============================================================================
def affine_keys(keys):
    """
    for affine method, check if keys containes a - example of key wanted = 15-23  (format 15*x + 23 modulo 26)
    
    ici on decoupe la clé en deuxclé differentes 15-23 devient jey1 = 15 et key2 = 23
    """
    if(not affine_keys_valid):
        print("probleme format keys affine")
        return False
    key1 = ""
    key2 = ""
    seconde_cle = False
    for letter in keys:
        if seconde_cle:
            key2 += letter
        else:
            if letter == '-' and not seconde_cle:
                seconde_cle = True
            else:
                key1 += letter
    if (not key1.isdigit() or not key2.isdigit()):
        print("affine keys not digit format")
        return False
    return [key1,key2]
        
def affine_keys_valid(keys):
    """ check si au moins 1 chiffre avant et apres le -"""
    if ('-' in keys):
        if (keys[0] != '-' and keys[len(keys)-1] != '-'):
            print("format validé affine key valid")
            return True
        else:
            print("erreur au sein de la fonction affine key valid")
    return False
#=============================================================================



#-----------------------------------------------------------------------------
def envoyer(key, code):
    """ determine le resultat du codage ou decodage demandé"""
    if(encode_decode_.get()==1):
        encode_decode = "encode"
    else:
        encode_decode="decode"
    type_code = variable.get()
    keys = key
    cod = code   
    if(valider_cle(type_code, keys)):
        if (type_code == "Affine"):
            liste = affine_keys(keys)
            keys1 = liste[0]
            keys2 = liste[1]
            
            keys1 = int(keys1)
            keys2 = int(keys2)
                        
            result = fn.resultat(type_code, encode_decode, keys1, cod, keys2)
        else:
            result = fn.resultat(type_code, encode_decode, keys, cod)  
        print(result)
    else:
        result = "la clé ne correspond pas au type de code demandé"
    return result
#-----------------------------------------------------------------------------    



#_____________________________________________________________________________
def affichage(key, code):
    """ affiche le message codé ou decodé en reponse"""
    result = envoyer(key, code)
    return result
    
def getKey():
    res = saisie3.get(pos31, 'end-1c')
    return res
    
def getCode():
    res = saisie4.get(pos41, pos42)
    return res

def functionAffichage():
    key = getKey()
    code = getCode()
    return affichage(key, code)

def affichageCode():    
    saisie5.delete(pos51, pos52)
    saisie5.insert(pos51, functionAffichage())

def effacerCode():
    saisie4.delete(pos41, pos42)
    saisie5.delete(pos51, pos52)
#_____________________________________________________________________________    
    
    
fenetre = tk.Tk()
fenetre.title('Cryptographie à clé secrète')
    
label1 = tk.Label(fenetre, text = "Type de code :").grid(row=0, column = 0)
label2 = tk.Label(fenetre, text = "Encoder ou décoder :").grid(row=1, column = 0)
label3 = tk.Label(fenetre, text = "Clé de chiffrement :").grid(row=2, column = 0)
label4 = tk.Label(fenetre, text = "Message à coder ou décoder :").grid(row=3, column = 0)
label5 = tk.Label(fenetre, text = "Message codé ou décodé :").grid(row=4, column = 0)
    
OptionList = ["Cesar", "Wegner", "Affine", "RC4"]
variable = tk.StringVar(fenetre)
variable.set(OptionList[0])
opt = tk.OptionMenu(fenetre, variable, *OptionList)
opt.config(width = 10, font=('Helvetica', 12))
opt.grid(row=0, column = 1)

# ===== saisie clé =======
saisie3 = tk.Text(fenetre)
pos3 = "0.0"
pos31 = "0.0"
pos32 = tk.END
saisie3.config(width = 31, height = 2)
saisie3.grid(row=2, column = 1, columnspan=2)

# ===== saisie message à coder ou décoder =======
saisie4 = tk.Text(fenetre)
pos4 = "0.0"
pos41 = "0.0"
pos42 = tk.END
saisie4.config(width = 31, height = 6)
saisie4.grid(row=3, column = 1, columnspan=2)

# ===== retour message codé ou décodé =======
saisie5 = tk.Text(fenetre)
pos5 = "0.0"
pos51 = "0.0"
pos52 = tk.END
saisie5.config(width = 31, height = 6)
saisie5.grid(row=4, column = 1, columnspan=2)

  
encode_decode_ = tk.IntVar()
encode = tk.Radiobutton(fenetre, text = "encode", variable = encode_decode_, value = 1).grid(row=1, column=1)
decode = tk.Radiobutton(fenetre, text = "decode", variable = encode_decode_, value = 2).grid(row=1, column=2)
    
   
tk.Button(fenetre, text="QUITTER", command = fenetre.destroy, fg="red").grid(row = 10, column = 0)
tk.Button(fenetre, text="EFFACER", command = effacerCode).grid(row = 10, column = 1)
tk.Button(fenetre, text="VALIDER", command = affichageCode, fg="green").grid(row = 10, column = 2)


fenetre.mainloop()