import ocyan.core.plugins


class BlockPluginConfig(ocyan.core.plugins.OcyanPluginConfig):
    def contribute_to_blocks(self, blocks):
        # NOOP to allow pipeing with straight.plugin
        return blocks

    def contribute_to_ocyan_settings_blocks(self, blocks):
        return blocks


def get_block_plugins():
    return ocyan.core.plugins.get_plugins(cls=BlockPluginConfig)


def get_block_choices(context=None, **kwargs):
    kwargs.setdefault("initial_blocks", [])

    blocks = get_block_plugins()
    available_blocks = (
        blocks.pipe("contribute_to_blocks", kwargs["initial_blocks"]) or []
    )
    if context is None:
        return [(block[0], block[1]) for block in available_blocks]

    # if a filter was passed we should check if the block was regostered with
    # a third argument and filter on this third argument.
    selected_blocks = []
    for block in available_blocks:
        try:
            label, block, ctx = block
            if context in ctx:
                selected_blocks.append((label, block))
        except ValueError:
            selected_blocks.append((block[0], block[1]))

    return selected_blocks


def get_extra_ocyan_settings_blocks():
    blocks = get_block_plugins()
    return blocks.pipe("contribute_to_ocyan_settings_blocks", []) or []
