"""Provides the options command."""

from functools import partial
from gsb.intercept import Menu
from forms import set_value
from parsers import parser
from options import options
from util import done


def show_section(section, caller):
    """Show the player an instance of OptionsMenu."""
    caller.connection.notify(OptionsMenu, section)


def show_option(option, caller):
    """Show and edit an option."""
    player = caller.connection.player

    def invalid_input(caller):
        """Show invalid input warning."""
        player.notify('Invalid input: %r.', caller.text)
        show_section(option.section, caller)

    def after(caller):
        """Set the value."""
        done(player)
        show_section(option.section, caller)

    value = getattr(player.options, option.name)
    if value is True:
        value = 'Enabled'
    elif value is False:
        value = 'Disabled'
    elif value is None:
        value = 'Clear'
    else:
        value = repr(value)
    player.notify(
        '%s\n%s\nCurrent value: %s\n',
        option.friendly_name,
        option.description,
        value
    )
    set_value(
        player.options,
        option.name,
        caller,
        after=after,
        invalid_input=invalid_input
    )


class OptionsMenu(Menu):
    """Show all the sub-sections and the options of a section."""

    def __init__(self, section):
        self.section = section
        super(OptionsMenu, self).__init__(
            title='%s\n%s' % (
                section.name,
                section.description
            ),
            restore_parser=parser
        )

    def explain(self, connection):
        """Build the menu."""
        player = connection.player
        self.items.clear()
        self.labels.clear()
        if self.section.sections or self.section.parent is not None:
            self.add_label('Sections', None)
        for subsection in self.section.sections:
            if subsection.allowed is None or subsection.allowed(player):
                self.item(subsection.name)(partial(show_section, subsection))
        if self.section.parent is not None:
            self.item('Back to %s' % self.section.parent.name)(
                partial(show_section, self.section.parent)
            )
        if self.items:
            after = self.items[-1]
        else:
            after = None
        if self.section.options:
            self.add_label('Options', after)
        for option in self.section.options:
            

        return super(OptionsMenu, self).explain(connection)


@parser.command
def do_options(caller):
    """options

    Set options for your player."""
    show_section(options, caller)

self.item(option.friendly_name)(partial(show_option, option))