# -*- coding: utf-8 -*-
import Tkinter
import tkFont


class Window(Tkinter.Tk):
    def __init__(self, parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent

    def initialize(self):
        pass


class Listbox(Tkinter.Listbox):
    def autowidth(self, maxwidth):
        f = tkFont.Font(font=self.cget("font"))
        pixels = 0
        for item in self.get(0, "end"):
            pixels = max(pixels, f.measure(item))
        # bump listbox size until all entries fit
        pixels +=10
        width = int(self.cget("width"))
        for w in range(0, maxwidth+1, 5):
            if self.winfo_reqwidth() >= pixels:
                break
            self.config(width=width+w)


class CommonFrame(Tkinter.Frame):
    """Common class for displaying UIs"""
    def __init__(self, parent, core):
        """

        :param parent: the containing Tkinter object
        :param core: the MicroFTPCore object
        :return:
        """
        self.core = core
        Tkinter.Frame.__init__(self, parent)
        self.pack(expand=1, fill='both')
        self.parent = parent
        self.controls = {}
        self.init_controls()
        self.show_controls()

    def init_controls(self):
        pass

    def show_controls(self):
        pass

    def hide_view(self, widgets_to_destroy):
        """Un-show widgets

        :param widgets_to_destroy: list of widgets to .destroy()
        :return:
        """
        self.hide_controls(widgets_to_destroy)
        self.pack_forget()

    def hide_controls(self, widgets_to_destroy=None):
        """Hide visible widgets, leaving only blank frame

        :param widgets_to_destroy: list of widgets that should be .destroy()ed rather than hidden
        :return:
        """
        for control in self.controls:  # order isn't important
            self.controls[control].pack_forget()
        if widgets_to_destroy:
            for widget in widgets_to_destroy:
                widget.destroy()

    def show_error(self, error_msg):
        """Hide everything, display an error message and a 'Back' button

        :param error_msg: the message to show
        :return:
        """
        def reset_view(widgets_to_destroy):
            self.hide_controls(widgets_to_destroy)
            self.show_controls()
        error_widgets = []
        error_text = Tkinter.Label(self.parent, text=error_msg)
        error_text.pack()
        error_widgets.append(error_text)
        back_button = Tkinter.Button(self.parent, text="Back", command=lambda: reset_view(error_widgets))
        back_button.pack()
        error_widgets.append(back_button)



