import curses
from Queue import Queue
from time import strftime

class BaseWindow(object):
    """
    Base class of the user interface window components.
    """

    def __init__(self, main, top, left, height, width):
        # Reference to the main window
        self.main = main

        # Window position
        self.top    = top
        self.left   = left
        self.height = height
        self.width  = width

        self.lines = []
        self.line_queue = Queue()

        # Initialise window
        self.window = curses.newwin(height, width, top, left)

    def clear(self):
        """
        Clear the window object. This will hide all rows (but does not discard
        the buffer containing all message).
        """
        self.window.clear()
        self.refresh()

    def redraw(self):
        """
        Clear the window object and draw the rows containing last appended
        messages in the window object. If not all message fit in the window, the
        last appended messages are shown (last appended message is displayed as
        last message) and the messages which do not fit are not displayed.
        """
        self.window.clear()

        while not self.line_queue.empty():
            self.lines.append(self.line_queue.get())

        if hasattr(self,'displayed_help') and self.displayed_help:
            return

        for y, line in enumerate(self.lines[-self.height:]):
            try:
                self.window.addstr(y, 0, line.ljust(self.width))
            except curses.error:
                pass
        self.refresh()

    def refresh(self):
        self.window.refresh()

    def append(self, msg):
        """
        Add a message to the bottom of the window. This will move all messages
        one row up.
        """
        time_prefix = strftime('%H:%M') + ' '
        while msg:
            msg = time_prefix + msg
            self.line_queue.put(msg[:self.width])
            msg = msg[self.width:]
        self.redraw()

