#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 5.4
#  in conjunction with Tcl version 8.6
#    Sep 25, 2020 06:38:15 PM -03  platform: Windows NT
import os
import sys

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

from tkinter.filedialog import askopenfilename
from tkinter import messagebox
import interface_compilador_support
sys.path.append(os.path.abspath('../sintatico'))
sys.path.append(os.path.abspath('../lexico'))
from Sintatico import Sintatico
from Lexico import Lexico

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.Tk()
    top = Toplevel1 (root)
    interface_compilador_support.init(root, top)
    root.mainloop()

w = None
def create_Toplevel1(rt, *args, **kwargs):
    '''Starting point when module is imported by another module.
       Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .'''
    global w, w_win, root
    #rt = root
    root = rt
    w = tk.Toplevel (root)
    top = Toplevel1 (w)
    interface_compilador_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_Toplevel1():
    global w
    w.destroy()
    w = None

class Toplevel1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        self.txt_arquivo = ""

        top.geometry("1636x889+259+69")
        top.minsize(148, 1)
        top.maxsize(4804, 1325)
        top.resizable(1, 1)
        top.title("Compilador")
        top.configure(background="#d9d9d9")

        self.Frame1 = tk.Frame(top)
        self.Frame1.place(relx=0.006, rely=0.011, relheight=0.085, relwidth=0.987)
        self.Frame1.configure(relief='groove')
        self.Frame1.configure(borderwidth="2")
        self.Frame1.configure(relief="groove")
        self.Frame1.configure(background="#d9d9d9")

        self.Button_abrir = tk.Button(self.Frame1)
        self.Button_abrir.place(relx=0.020, rely=0.154, height=43, width=216)
        self.Button_abrir.configure(activebackground="#ececec")
        self.Button_abrir.configure(activeforeground="#000000")
        self.Button_abrir.configure(background="#d9d9d9")
        self.Button_abrir.configure(disabledforeground="#a3a3a3")
        self.Button_abrir.configure(foreground="#000000")
        self.Button_abrir.configure(highlightbackground="#d9d9d9")
        self.Button_abrir.configure(highlightcolor="black")
        self.Button_abrir.configure(pady="0")
        self.Button_abrir.configure(text='''ABRIR''')
        self.Button_abrir.configure(fg="black")
        self.Button_abrir.configure(font="Arial 12")
        self.Button_abrir.configure(command=self.abrir_arquivo)

        self.Button_salvar = tk.Button(self.Frame1)
        self.Button_salvar.place(relx=0.170, rely=0.154, height=43, width=216)
        self.Button_salvar.configure(activebackground="#ececec")
        self.Button_salvar.configure(activeforeground="#000000")
        self.Button_salvar.configure(background="#d9d9d9")
        self.Button_salvar.configure(disabledforeground="#a3a3a3")
        self.Button_salvar.configure(foreground="#000000")
        self.Button_salvar.configure(highlightbackground="#d9d9d9")
        self.Button_salvar.configure(highlightcolor="black")
        self.Button_salvar.configure(pady="0")
        self.Button_salvar.configure(text='''SALVAR''')
        self.Button_salvar.configure(fg="black")
        self.Button_salvar.configure(font="Arial 12")

        self.Button_compilar = tk.Button(self.Frame1)
        self.Button_compilar.place(relx=0.320, rely=0.154, height=43, width=216)
        self.Button_compilar.configure(activebackground="#ececec")
        self.Button_compilar.configure(activeforeground="#000000")
        self.Button_compilar.configure(background="#d9d9d9")
        self.Button_compilar.configure(disabledforeground="#a3a3a3")
        self.Button_compilar.configure(foreground="#000000")
        self.Button_compilar.configure(highlightbackground="#d9d9d9")
        self.Button_compilar.configure(highlightcolor="black")
        self.Button_compilar.configure(pady="0")
        self.Button_compilar.configure(text='''COMPILAR''')
        self.Button_compilar.configure(fg="black")
        self.Button_compilar.configure(font="Arial 12")
        self.Button_compilar.configure(command=self.compilar)

        self.Listbox_programa = tk.Listbox(top)
        self.Listbox_programa.place(relx=0.006, rely=0.146, relheight=0.841, relwidth=0.571)
        self.Listbox_programa.configure(background="white")
        self.Listbox_programa.configure(disabledforeground="#a3a3a3")
        self.Listbox_programa.configure(font="TkFixedFont")
        self.Listbox_programa.configure(foreground="#000000")

        self.Listbox_console = tk.Listbox(top)
        self.Listbox_console.place(relx=0.587, rely=0.146, relheight=0.841, relwidth=0.406)
        self.Listbox_console.configure(background="white")
        self.Listbox_console.configure(disabledforeground="#a3a3a3")
        self.Listbox_console.configure(font="TkFixedFont")
        self.Listbox_console.configure(foreground="#000000")

        self.title_programa = tk.Label(top)
        self.title_programa.place(relx=0.073, rely=0.110, height=26, width=601)
        self.title_programa.configure(background="#d9d9d9")
        self.title_programa.configure(disabledforeground="#a3a3a3")
        self.title_programa.configure(foreground="#000000")
        self.title_programa.configure(text='''Programa''')
        self.title_programa.configure(fg="navy blue")
        self.title_programa.configure(font="Helvetica 16 bold")

        self.title_console = tk.Label(top)
        self.title_console.place(relx=0.623, rely=0.110, height=26, width=569)
        self.title_console.configure(background="#d9d9d9")
        self.title_console.configure(cursor="fleur")
        self.title_console.configure(disabledforeground="#a3a3a3")
        self.title_console.configure(foreground="#000000")
        self.title_console.configure(text='''Console''')
        self.title_console.configure(fg="navy blue")
        self.title_console.configure(font="Helvetica 16 bold")

    def abrir_arquivo(self):
        self.txt_arquivo = ""
        self.lexemas_simbolos = []
        filename = askopenfilename() 
        try:
            with open(filename, "r", encoding="utf-8") as f:
                self.txt_arquivo = f.read()
        except:
            with open(filename, "r", encoding="iso-8859-1") as f:
                self.txt_arquivo = f.read()
        self.Listbox_programa.delete(0, tk.END)
        self.Listbox_console.delete(0, tk.END)
        for line in self.txt_arquivo.split('\n'):
            if len(line)>0:
                self.Listbox_programa.insert(tk.END, line)


    def compilar(self):
        s = Sintatico(txt=self.txt_arquivo)
        try:
            s.analisa_programa()
            for i in reversed(s.semantico.assemble):
                if i['comando'] == 'NULL':
                    i['comando'] = "L"+str(i['rotulo'])
                    attr1 = "NULL"
                # elif i['rotulo']:
                    # attr1 = "L"+str(i['rotulo'])
                    # attr2 = ""
                else:
                    attr1 = i['attr1'] if i['attr1'] is not None  else ''
                    attr2 = ", "+str(i['attr2']) if i['attr2'] is not None else ''
                self.Listbox_console.insert(tk.END, i['comando']+" "+str(attr1)+" "+attr2+"\n")

            with open('cod_saida.txt', 'w') as f:
                for i in reversed(s.semantico.assemble):
                    if i['comando'] == 'NULL':
                        i['comando'] = "L"+str(i['rotulo'])
                        attr1 = "NULL"
                    # elif i['rotulo']:
                        # attr1 = "L"+str(i['rotulo'])
                        # attr2 = ""
                    else:
                        attr1 = i['attr1'] if i['attr1'] is not None  else ''
                        attr2 = ", "+str(i['attr2']) if i['attr2'] is not None else ''
                    f.write(i['comando']+" "+str(attr1)+" "+attr2+"\n")

        except Exception as e:
            linha = str(e).split()[-1]
            self.Listbox_programa.itemconfig(int(linha)-1, {'bg':'red'})
            messagebox.showinfo("Erro", str(e))


if __name__ == '__main__':
    vp_start_gui()


