from behave import then

from MMTest.variables.models import Variable
from MMTest.implementations.models import Implementation


def variable_table_data(context):
    data = []
    variable_section = context.browser.find_element_by_id('interface')
    rows = variable_section.find_elements_by_tag_name('tr')
    for row in rows:
        columns = row.find_elements_by_tag_name('td')
        if columns:
            data.append({
                'name': columns[0].text,
                'description': columns[1].text,
                'variable_type': columns[2].text,
                'data_type': columns[3].text,
            })
    return data


def implementation_table_data(context):
    data = []
    implementation_section = context.browser.find_element_by_id(
            'implementations')
    rows = implementation_section.find_elements_by_tag_name('tr')
    for row in rows:
        columns = row.find_elements_by_tag_name('td')
        if columns:
            data.append({'name': columns[0].text,
                         'description': columns[1].text,
                         })

    return data


@then('Lista de variáveis do modelo é apresentada')
def model_details_show_var_list(context):
    variables = Variable.objects.filter(mathmodel=context.current_mathmodel)
    variable_info = [(variable.name,
                      variable.description,
                      variable.get_variable_type_display(),
                      variable.get_data_type_display(),
                      ) for variable in variables]

    table_data = variable_table_data(context)
    rows_info = [(data['name'],
                  data['description'],
                  data['variable_type'],
                  data['data_type'],
                  ) for data in table_data]

    context.test.assertListEqual(variable_info, rows_info)


@then('Lista de implementações do modelo é apresentada')
def model_details_show_impl_list(context):
    implementations = Implementation.objects.filter(
            mathmodel=context.current_mathmodel)
    implementation_info = [(implementation.name, implementation.description)
                            for implementation in implementations]

    table_data = implementation_table_data(context)
    rows_info = [(data['name'], data['description']) for data in table_data]

    context.test.assertListEqual(implementation_info, rows_info)
