import h5py
import pytest

from ..tasks import positioner_utils


@pytest.fixture(scope="module")
def example_bliss_scan_uri(tmpdir_factory):
    filename = str(tmpdir_factory.mktemp("test_positioners").join("data.h5"))
    with h5py.File(filename, mode="w") as root:
        dset = root.create_dataset(
            "/1.1/instrument/positioners_start/energy", data=10.0
        )
        dset.attrs["units"] = "keV"
        dset = root.create_dataset(
            "/1.1/instrument/positioners_start/energy_und",
            data=[10.0, 10.0, 10.0000001],
        )
        dset = root.create_dataset("/1.1/instrument/other/name", data=11.0)
    return f"{filename}::/1.1"


def test_get_energy(example_bliss_scan_uri):
    value = positioner_utils.get_primary_beam_energy_value(example_bliss_scan_uri)
    assert value is None
    value = positioner_utils.get_primary_beam_energy_value(
        example_bliss_scan_uri, search_on_units=True
    )
    assert value == 10.0
    value = positioner_utils.get_primary_beam_energy_value(
        example_bliss_scan_uri, energy_name="energy"
    )
    assert value == 10.0
    value = positioner_utils.get_primary_beam_energy_value(
        example_bliss_scan_uri, energy_name="energy_und"
    )
    assert value == 10.0
    value = positioner_utils.get_primary_beam_energy_value(
        example_bliss_scan_uri,
        energy_name="energy",
        energy_uri_template="instrument/positioners_start/{}",
    )
    assert value == 10.0
    value = positioner_utils.get_primary_beam_energy_value(
        example_bliss_scan_uri,
        energy_name="name",
        energy_uri_template="instrument/other/{}",
    )
    assert value == 11.0


def test_get_energy_suburi(example_bliss_scan_uri):
    value = positioner_utils.get_primary_beam_energy_suburi(example_bliss_scan_uri)
    assert value == "instrument/positioners_start/energy"
