import Tkinter as tk
import base64
import os
import time
import sys

from log import logTC
from log import logStart

from errorwin import ErrorWindow

from mainloop import runMain

from imgcode import logo

PADX = 10
PADY = 10

from cfg import Config
Config = Config()

authPresent = False

logTC("Verifying authfile...")
try:
    from auth import getOPW
    logTC("Authfile successfully verified.")
    logTC("Beginning authentication...")
    authPresent = True
except ImportError:
    logTC("Authfile not found!", "ERROR") 
    authPresent = False
    
def auth(*argv):
    class AuthWindow(tk.Frame):
        def __init__(self, parent, *args, **kwargs):
            if not True:
                #old code: to be removed
                logTC("Authfile not found!", "FATAL")
                error = ErrorWindow(self, "Authfile not found!", "400x100")
            else:
                tk.Frame.__init__(self, parent, *args, **kwargs)
                self.parent = parent

                self.logo = tk.PhotoImage(data=logo)
                self.logoLabel = tk.Label(image=self.logo)
                self.logoLabel.pack()

                self.titleLabel = tk.Label(text="Digital Visitor Card Log",
                                           font=("Arial", 16, "bold"))
                self.titleLabel.pack()

                if Config.dispSAM:
                    self.subtitleLabel = tk.Label(text="\"Still better than SAM.\"",
                                                  font=("Arial", 10))
                    self.subtitleLabel.pack(pady=PADY)

                self.pwINSLabel = tk.Label(text="Enter Password:")
                self.pwINSLabel.pack()

                self.pwEntryVar = tk.StringVar(self)
                self.pwEntry = tk.Entry(self, show="*", textvariable=self.pwEntryVar, width=30)
                self.pwEntry.bind("<Return>", lambda _: self.validate())
                self.pwEntry.pack(padx=PADX, pady=PADY)
                self.pwEntry.focus_set()
                self.pwEntryVar.trace("w", self.detectEmpty)

                self.incorrectLabel = tk.Label(self, text="")
                self.incorrectLabel.pack()

                self.enterButton = tk.Button(self, text="Enter", width=15, command=self.validate)
                self.bind("<Return>", self.validate)
                self.enterButton.pack(padx=PADX, pady=PADY)

                if not os.path.isfile('auth.pyc'):
                    error = ErrorWindow(self, "Auth file not present. Please see an administrator.")

        def validate(self, *args):
            if not os.path.isfile('auth.pyc'):
                error = ErrorWindow(self, "Auth file not present. Please see an administrator.")
            else:
                inpt = self.pwEntryVar.get()
                inpt = base64.b64encode(inpt)
                if inpt == getOPW():
                    logTC("Password authentication successful.")
                    self.close1()
                elif inpt == "":
                    self.incorrectLabel.configure(text="Password field blank")
                    logTC("Authentication failed.")
                else:
                    self.incorrectLabel.configure(text="Incorrect password")
                    logTC("Authentication failed.")
                    
        def close0(self, *args):
            self.parent.destroy()

        def close1(self, *args):
            self.parent.destroy()
            runMain()

        def detectEmpty(self, *args):
            self.incorrectLabel.configure(text="")

    root = tk.Tk()
    root.geometry("400x325")
    root.title("Enter Password")
    AuthWindow(root).pack(side="top", fill="both", expand=True)
    root.mainloop()
