class TelaPrincipal:
    def __init__(self):
        """
        """

        self.root = Tk()
        self.root.title("Radar RFID")
        self.root.resizable(False, False)

        w = self.root.winfo_screenwidth()
        h = self.root.winfo_screenheight()

        x = (w - self.root.winfo_reqwidth()) / 2
        y = (h - self.root.winfo_reqheight()) / 2

        self.root.geometry("+%d+%d" % (x - 200, y - 200))

        self.app = Application()

        self.thread_radar = threading.Thread(target=self.start_radar)
        self.thread_radar.setDaemon(True)

    def open_window(self):

        self.build_window()
        self.root.mainloop()

    def build_window(self):
        """

        :return:
        """

        main_frame = Frame(self.root)
        main_frame.pack()

        # submenu
        upper_menu = Menu(self.root, relief='groove')

        self.root['menu'] = upper_menu

        sub_menu_cadastro = Menu(upper_menu)
        sub_menu_cadastro.add_command(label="Veículos",
                                      command=self.open_veiculos)
        sub_menu_cadastro.add_command(label="Leitoras",
                                      command=self.open_leitoras)
        upper_menu.add_cascade(menu=sub_menu_cadastro, label="Cadastro")

        sub_menu_registros = Menu(upper_menu)
        sub_menu_registros.add_command(label="Infrações",
                                       command=self.open_registros)
        upper_menu.add_cascade(menu=sub_menu_registros, label="Registros")

        img = PhotoImage(file='dummy.png')
        self.graf = Label(main_frame, image=img)
        self.graf.image = img
        self.graf.grid(row=1, column=0, columnspan=4)

        bt_iniciar = Button(main_frame,
                            text="Iniciar",
                            command=lambda: self.thread_radar.start())
        bt_iniciar.grid(row=0, column=3, padx=10, pady=5, sticky='e')

        # saida

        label_debugg = Label(main_frame, text="Detecções:")
        label_debugg.grid(row=9, column=0, pady=5, sticky='w')
        self.debugg = Text(main_frame, width=80, height=5)
        self.debugg.grid(row=10, column=0, columnspan=4, padx=10, pady=10)

    def open_veiculos(self):
        """

        :return:
        """
        janela_cadastro = CadastroVeiculo(self.root)
        janela_cadastro.open_window()

    def open_leitoras(self):
        """

        :return:
        """
        janela_leitoras = CadastroLeitora(self.root)
        janela_leitoras.open_window()

    def open_registros(self):
        """

        :return:
        """
        janela_reg = Registros(self.root)
        janela_reg.open_window()

    def start_radar(self):

        self.debugg.insert(CURRENT, "Iniciando Simulação...\n")
        self.fig = plt.figure()
        while 1:

            output = self.app.execute_radar()

            if output is not None:
                self.debugg.insert(END, output)
                self.debugg.see(END)
                self.plot_grafico()

            # time.sleep(1)

    def plot_grafico(self):

        infractions = self.app.get_infracoes()

        if len(infractions) > 0:
            infr_counter = Counter(elem[2] for elem in infractions)

            labels = list(infr_counter.keys())
            counters = list(infr_counter.values())
        else:
            labels = "Tipo 1", "Tipo 2", "tipo 3"
            counters = 0, 0, 0

        plt.bar(labels, counters, align='center', alpha=0.5, color='b')
        plt.ylabel('Nº Ocorrências')
        plt.xlabel('Tipo de Infração')
        plt.title("Frequência de Infrações")
        plt.savefig('plot.png', transparent=True)
        self.fig.clf()

        img = PhotoImage(file='plot.png')
        self.graf.image = img
        self.graf.config(image=img)
        self.graf.image = img
class Registros:
    def __init__(self, master):

        self.this = Toplevel(master)
        self.this.title("Registros")
        self.this.resizable(False, False)

        w = self.this.winfo_screenwidth()
        h = self.this.winfo_screenheight()

        x = (w - self.this.winfo_reqwidth()) / 2
        y = (h - self.this.winfo_reqheight()) / 2

        self.this.geometry("+%d+%d" % (x - 150, y - 150))

        self.app = Application()

        self.infracoes_cadastradas = []

    def build_window(self):
        """

        :return:
        """

        main_frame = Frame(self.this)
        main_frame.pack()

        self.tabela_registros = ttk.Treeview(main_frame,
                                             selectmode="browse",
                                             show='headings')

        ttk.Style().configure("Treeview", width=50)

        self.tabela_registros['columns'] = '1', '2', '3'

        self.tabela_registros.column('#1', width='100')
        self.tabela_registros.heading('#1', text='Placa')

        self.tabela_registros.column('#2', width='200')
        self.tabela_registros.heading('#2', text='Tag')

        self.tabela_registros.column('#3', width='100')
        self.tabela_registros.heading('#3', text='Infração')

        self.tabela_registros.grid(row=5,
                                   column=0,
                                   columnspan=5,
                                   padx=5,
                                   pady=10)

        scroll_bar_tree_vertical = Scrollbar(main_frame, relief='flat')
        scroll_bar_tree_vertical.grid(row=5,
                                      column=6,
                                      sticky=('w', 'e', 'n', 's'))

        self.tabela_registros.config(
            yscrollcommand=scroll_bar_tree_vertical.set)
        scroll_bar_tree_vertical.config(command=self.tabela_registros.yview)

        self.popular_tabela()

    def popular_tabela(self):
        """

        :return:
        """

        if len(self.tabela_registros.get_children()) > 0:
            self.tabela_registros.delete(*self.tabela_registros.get_children())

        self.infracoes_cadastradas = self.app.get_infracoes()

        row = 0
        for registro in self.infracoes_cadastradas:

            self.tabela_registros.insert(
                "",
                row,
                iid=int(row),
                values=[registro[0], registro[1], registro[2]])

            row += 1

    def open_window(self):
        self.build_window()
        self.this.mainloop()

    def close_window(self):
        self.this.destroy()