# -*- coding: utf-8 -*-
from tkinter import Frame,StringVar,TOP, Entry,LEFT,Button,BOTTOM, Text, END,INSERT, Tk
from tkinter import filedialog
import os

from string import ascii_letters

class Cesar:

    def __init__(self, master):

        frameHaut = Frame(master)
        frameHaut.pack(side=TOP)
        
        
        self.nomFichier = StringVar()
        self.wNomFichier = Entry(frameHaut, textvariable=self.nomFichier)
        self.wNomFichier.pack(side=LEFT)

        #option pour chercher dans le SDF
        self.open_button = Button(frameHaut)
        self.open_button['text'] = "chercher"
        self.open_button['command'] = self.askOpenFile
        self.file_opt = options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('all files', '.*'), ('text files', '.txt'),('python file','.py')]
        options['initialdir'] = 'C:\\'
        options['initialfile'] = ''
        options['parent'] = master
        options['title'] = 'This is a title'
        self.open_button.pack(side=LEFT)


        self.b_coder = Button(frameHaut, fg="red")
        self.b_coder['text'] = "coder"
        self.b_coder['command'] = self.coderCesar
        self.b_coder.pack(side=LEFT)

        self.button = Button(frameHaut)
        self.button['text'] = "QUIT"
        self.button['fg'] = "red"
        self.button['command'] = master.quit
        self.button.pack(side=LEFT)
        
        
        frameBas = Frame(master)
        frameBas.pack(side=BOTTOM)
        
        self.wText = Text(frameBas)
        self.wText.pack()

    def askOpenFile(self):
        """

        :return:
        """
        pathFilename = filedialog.askopenfilename( **self.file_opt)
        self.nomFichier.set(pathFilename)

    def coderCesar(self):
        """ coder la saisie de l'utilisateur. Est ce un fichier ascii ou seulement du texte ?"""
        cheminFichier = self.nomFichier.get()
        if not os.path.isfile(cheminFichier):
            texte = cheminFichier
        else:
            with open(cheminFichier,'r') as fichierOuvert:
                texte = fichierOuvert.read()

            
        #approche 1
        textCode = ''.join([(lettre in ascii_letters and ascii_letters[(ascii_letters.index(lettre)+13) % len(ascii_letters)]) or lettre for lettre in texte])
        
        
        #approche 2
        textCode = ''
        for lettre in texte:
            if lettre in ascii_letters:
                indice_code = (ascii_letters.index(lettre)+13 ) % len(ascii_letters)
                textCode +=  ascii_letters[indice_code]
            else:
                textCode += lettre
                
        self.wText.delete(1.0, END)
        self.wText.insert(INSERT, textCode)

if __name__ ==  '__main__':
    root = Tk()

    app = Cesar(root)

    root.mainloop()
