import curses
from curses.textpad import Textbox
import re

from base_bar import BaseBar

class CommandBar(BaseBar):
    """
    Command bar is part of the Command Line Interface (CLI) of the chat
    application. The command bar is responsible for handling the user input.
    This includes executing commands and (re)drawing the command line.
    """
    def __init__(self, main, top, left, width):
        super(CommandBar, self).__init__(main, top, left, width)

        # Initialise textbox
        self.textbox = Textbox(self.bar)

    def focus(self):
        """
        Set the cursor to the current positon of this bar.
        """
        self.bar.move(*self.bar.getyx())

    def handle_input(self, c):
        #if c == curses.KEY_HOME:
        #    self.x = self.y = 0
        #elif 32 <= c <= 127:
        #    self.append_command(c)
        self.append_command(c)

    def append_command(self, c):
        if not self.textbox.do_command(c):
            self.execute_command()
        self.bar.refresh()

    def execute_command(self, command=''):
        if not command:
            # Clear command bar, reset cursor and redraw the command bar.
            command = self.textbox.gather()
            self.bar.deleteln()
            self.bar.move(0, 0)

        command = command.strip()

        if not command:
            return

        if command[0] == '/':
            # Split command line into command identifier and arguments.
            parts = re.split('\s+', command)
            cmd = parts[0][1:]
            args = parts[1:]

            self.main.execute(cmd, args, command)
        else:
            # User sends a chat message.
            self.main.say(command)

