#TODO: add a password prompter
#TODO: Fix up the size of the text window

import os
from Tkinter import *
from ScrolledText import *
from tkFileDialog import *
import tkSimpleDialog

def encrypt_xor(inString, password):
    outString = ""
    password = password.replace(" ", "s")
    for ch in inString:
        for pch in password:
            ch = chr(ord(ch)^ord(pch))
        outString = outString + ch
    return outString

def encrypt_xor_fast(inString, password):
    outString = ""
    password = password.replace(" ", "s")
    cached=dict()
    for ch in inString:
        if (cached.get(ch)==None):
            enc = ch
            for pch in password:
                enc = chr(ord(enc)^ord(pch))
            cached[ch]=enc
        outString = outString + cached[ch]
    return outString

def encrypt_file(inFileName, outFileName, password):
    inFile = open(inFileName)
    inString = inFile.read()
    outString = encrypt_xor(inString, password)
    outFile = open(outFileName, "w")
    outFile.write(outString)

def open_command():
    global textWidget
    file = askopenfile()
    contents = file.read()
    textWidget.insert(END, contents)

def save_command():
    global textWidget
    file = asksaveasfile()
    contents = textWidget.get("1.0", END)
    file.write(contents)
    file.close()

def encrypt_command():
    global textWidget
    password = tkSimpleDialog.askstring("Password", "Please Enter your Password")
    contents = textWidget.get("1.0", END)
    encrypted = encrypt_xor_fast(contents, password)
    textWidget.delete("1.0", END)
    textWidget.insert(END, encrypted)

    
def hello():
    print("hello")

def exit_program():
    global root
    root.destroy()

root = Tk()

menuBar = Menu(root, tearoff=0)
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label="Open", command=open_command)
fileMenu.add_command(label="Save", command=save_command)
fileMenu.add_separator()
fileMenu.add_command(label="Quit", command=exit_program)
menuBar.add_cascade(label="File", menu=fileMenu)
encryptMenu = Menu(menuBar, tearoff=0)
encryptMenu.add_command(label="Encrypt", command=encrypt_command)
encryptMenu.add_command(label="Decrypt", command=encrypt_command)
menuBar.add_cascade(label="Encrypt", menu=encryptMenu)

textWidget = ScrolledText(root, width=80, height=50)
textWidget.grid(column=0,row=0,sticky="WENS")
textWidget.pack()

root.config(menu=menuBar)
root.mainloop()
                     
