# coding: utf-8

import os
import tempfile

import pytest
from silx.io.url import DataUrl

from tomoscan.io import HDF5File
from nxtomomill.converter.hdf5.acquisition.baseacquisition import (
    BaseAcquisition,
    get_dataset_name_from_motor,
)
from nxtomomill.io.config import TomoHDF5Config
from nxtomomill.tests.datasets import GitlabDataset
from nxtomomill import converter
from nxtomo.application.nxtomo import NXtomo
from nxtomo.nxobject.nxtransformations import get_lr_flip, get_ud_flip


def test_BaseAquisition():
    """simple test of the BaseAcquisition class"""

    with tempfile.TemporaryDirectory() as folder:
        file_path = os.path.join(folder, "test.h5")
        with HDF5File(file_path, mode="w") as h5f:
            h5f["/data/toto/dataset"] = 12

        url = DataUrl(file_path=file_path, data_path="/data/toto", scheme="silx")
        std_acq = BaseAcquisition(
            root_url=url,
            configuration=TomoHDF5Config(),
            detector_sel_callback=None,
            start_index=0,
        )
        with std_acq.read_entry() as entry:
            assert "dataset" in entry


def test_get_dataset_name_from_motor():
    """test get_dataset_name_from_motor function"""
    set_1 = ["rotation", "test1", "alias"]
    assert get_dataset_name_from_motor(set_1, "rotation") == "test1"
    assert get_dataset_name_from_motor(set_1, "my motor") is None

    set_2 = ["rotation", "test1", "alias", "x translation", "m2", "test1"]
    assert get_dataset_name_from_motor(set_2, "rotation") == "test1"
    assert get_dataset_name_from_motor(set_2, "x translation") == "m2"

    set_3 = ["rotation"]
    with pytest.raises(ValueError):
        get_dataset_name_from_motor(set_3, "rotation")


def test_frame_flips(tmp_path, monkeypatch):
    # make sure the result is obtained by using the "instrument/{active_config_tomo_detector}/data_axes" path.
    monkeypatch.setattr(
        "nxtomomill.converter.hdf5.acquisition.baseacquisition.BaseAcquisition._FRAME_FLIP_PATHS",
        ("instrument/{active_config_tomo_detector}/data_axes",),
    )

    scan_dir = GitlabDataset.get_dataset("h5_datasets")
    assert scan_dir is not None

    configuration = TomoHDF5Config()
    configuration.input_file = os.path.join(
        scan_dir, "frame_flip/quartz_nscope_pct_basler.h5"
    )
    configuration.output_file = os.path.join(tmp_path, "quartz.nx")
    configuration.single_file = True

    result = converter.from_h5_to_nx(configuration=configuration)
    assert os.path.exists(configuration.output_file)
    assert len(result) == 1

    nxtomo = NXtomo().load(*result[0])

    lr_flips = get_lr_flip(nxtomo.instrument.detector.transformations)
    assert len(lr_flips) == 1
    lr_flip = lr_flips[0]
    assert lr_flip is not None and lr_flip.transformation_values == 0
    ud_flips = get_ud_flip(nxtomo.instrument.detector.transformations)
    assert len(ud_flips) == 1
    ud_flip = ud_flips[0]
    assert ud_flip is not None and ud_flip.transformation_values == 0
