from showy.preprocess_utils import _has_stars
from showy.preprocess_utils import _replace_stars
from showy.preprocess_utils import _find_stars_values_in_string
from showy.preprocess_utils import _replace_stars_in_string
from showy.preprocess_utils import _collect_stars_values


def test_graph_layout_stars():
    graph_layout = {
        "curves": [{"var": "Y_*_min", "legend": "*"}],
        "x_var": "time",
        "y_label": "*",
        "x_label": "Time [s]",
        "title": "*",
    }

    assert _has_stars(graph_layout) is True

    available_varnames = ["Y_CO_min", "Y_CO2_min"]
    new_graph_layouts = _replace_stars(graph_layout, available_varnames)

    assert len(new_graph_layouts) == len(available_varnames)
    for name, graph_layout_ in zip(["CO", "CO2"], new_graph_layouts):
        assert graph_layout_["curves"][0]["var"] == f"Y_{name}_min"
        assert graph_layout_["curves"][0]["legend"] == name
        assert graph_layout_["y_label"] == name
        assert graph_layout_["title"] == name


def test_find_stars_in_string():
    available_varnames = ["Y_CO_min", "Y_CO_max", "Y_CO2_min", "Y_CO2_max"]

    # one star
    var_name = "Y_*_min"
    stars_values = _find_stars_values_in_string(var_name, available_varnames)

    target_values = ["CO", "CO2"]
    assert len(stars_values) == len(target_values)

    values = [value[0] for value in stars_values]
    for target_value in target_values:
        assert target_value in values

    # two stars
    var_name = "Y_*_*"
    stars_values = _find_stars_values_in_string(var_name, available_varnames)

    target_values = [("CO", "min"), ("CO", "max"), ("CO2", "min"), ("CO2", "max")]
    assert len(stars_values) == len(target_values)
    for target_value in target_values:
        assert target_value in stars_values


def test_replace_stars_in_string():

    # one star
    var_name = "Y_*"
    new_var_name = _replace_stars_in_string(var_name, ("1",))
    assert new_var_name == "Y_1"

    # two_stars
    var_name = "Y_*_*"
    new_var_name = _replace_stars_in_string(var_name, ("1", "2"))
    assert new_var_name == "Y_1_2"


def test_collect_stars_values():
    available_varnames = ["Y_CO_min", "Y_CO_max", "Y_CO2_min", "Y_CO2_max", "Y_O_max"]

    var_names = ["Y_*_min", "Y_*_max"]
    stars_values = _collect_stars_values(var_names, available_varnames)

    target_values = ["CO", "CO2"]
    assert len(stars_values) == len(target_values)

    values = [value[0] for value in stars_values]
    for target_value in target_values:
        assert target_value in values
