
import curses

class BaseBar(object):
    """
    Base class of the user inteface bar components.
    """

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

        # Bar position
        self.top   = top
        self.left  = left
        self.width = width

        # Initialise bar
        self.bar = curses.newwin(1, width, top, left)
        self.color_pair = curses.color_pair(0)
        self._prefix = ''

    def prefix(self, value=None):
        """
        Change or get the prefix of the bar. If value is None, the current
        prefix value is returned.
        """
        if value == None: # Note: an empty string can also be set.
            return self._prefix
        self._prefix = value
        self.display(self._msg)

    def display(self, msg):
        """
        Display a message on the bar. This will overwrite the currently
        displayed message. However, this will not overwrite the prefix value and
        this prefix value will be prepended to the message before displaying.
        """
        self._msg = msg
        if self.prefix():
            msg = self.prefix() + ' ' + msg
        # Curses will raise a 'curses.error' when the last possible character is
        # written. This exception should therefore always be catched. The raised
        # exception truncates the message to the width of the bar.
        try:
            self.bar.addstr(0, 0, msg.ljust(self.width), self.color_pair)
        except curses.error:
            pass
        self.refresh()

    def refresh(self):
        """
        Refresh the content of the bar.
        """
        self.bar.refresh()

