import logging
from behave import given, when, then

from penfold import PenfoldPluginManager
from penfold import InputOutputFactory

log = logging.getLogger(__name__)

@then(u'execute the plugin')
def execute_the_plugin(context):
    input_name1, input_value1 = context._first_input
    context._plugin.set_input_value(input_name1, input_value1)

    if context._second_input is not None:
        input_name2, input_value2 = context._second_input
        context._plugin.set_input_value(input_name2, input_value2)

    context._plugin.execute()
    context._output_values = context._plugin.output_values


@given(u'the name "{name}"  of a valid plugin')
def the_name_name__of_a_valid_plugin(context, name):
    context._first_input = None
    context._second_input = None
    context._plugin_name = name
    app = PenfoldPluginManager()
    plugin = app.get_plugin_by_name(context._plugin_name)
    context._plugin = plugin


@then(u'test that the output named "{output_name}" has the value "{output_value}"')
def test_that_the_output_named_outputname_has_the_value_outputvalue(context, output_name, output_value):
    log.debug("output={}".format(context._output_values[output_name]))
    assert str(context._output_values[output_name]) == output_value


@given(u'the value "{value}" of the first input "{name}"')
def the_value_value_of_the_first_input_input(context, name, value):
    context._first_input = (name, value)


@given(u'the value "{value}" of the second input "{name}"')
def the_value_of_the_second_input(context, value, name):
    context._second_input = (name, value)


@when(u'a set if input values is set')
def a_set_if_input_values_is_set(context):
    iof = InputOutputFactory()
    all_input_rows = []
    for row in context.table:
        input_set = []
        for i in range(len(row)):
            input_set.append(iof.create(row.headings[i], row[i]))
        all_input_rows.append(input_set)
    context._input_rows = all_input_rows
