from ...bliss_globals import setup_globals
from ...demo.processors.bm02 import DemoBm02XrpdProcessor
from ...demo.tests.utils.xrpd import _scan_context
from ...processor import BlissScanType
from .. import testing


@testing.integration_fixture
def bm02_xrpd_processor(gc_collect):
    bm02_processor = DemoBm02XrpdProcessor()
    bm02_processor.enable(setup_globals.difflab6)
    yield bm02_processor
    bm02_processor.disable_empty_cell_subtraction(setup_globals.difflab6)
    bm02_processor.disable()


def _scan(expo=0.2, npoints=10) -> BlissScanType:
    with _scan_context() as scans:
        scan = setup_globals.loopscan(npoints, expo, setup_globals.difflab6)
        scans.append(scan)
        return scan


def bm02_demo_1d(expo=0.2, npoints=10, ascii=False):
    test_bm02_1d(expo=expo, npoints=npoints, ascii=ascii)


@testing.integration_test
def test_bm02_1d(bm02_xrpd_processor, expo=0.2, npoints=10, ascii=False):
    bm02_xrpd_processor.ascii_export_enabled = ascii
    bm02_xrpd_processor.integration_options["difflab6"].pop("nbpt_azim", None)
    _scan(expo, npoints)
    testing.wait_workflows(raise_on_error=True)


def bm02_demo_2d(expo=0.2, npoints=10, ascii=False):
    test_bm02_2d(expo=expo, npoints=npoints, ascii=ascii)


@testing.integration_test
def test_bm02_2d(bm02_xrpd_processor, expo=0.2, npoints=10, ascii=False):
    bm02_xrpd_processor.integration_options["difflab6"]["nbpt_azim"] = 100
    bm02_xrpd_processor.ascii_export_enabled = ascii
    _scan(expo, npoints)
    testing.wait_workflows(raise_on_error=True)


def bm02_demo_1d_with_cell_subtraction(expo=0.2, npoints=10, ascii=False):
    test_bm02_1d_with_cell_subtraction(expo=expo, npoints=npoints, ascii=ascii)


@testing.integration_test
def test_bm02_1d_with_cell_subtraction(
    bm02_xrpd_processor, expo=0.2, npoints=10, ascii=False
):
    bm02_xrpd_processor.ascii_export_enabled = ascii
    bm02_xrpd_processor.integration_options["difflab6"].pop("nbpt_azim", None)

    # Do a first scan to be subtracted
    scan = _scan(expo, npoints)
    testing.wait_workflows(raise_on_error=True)
    scan_metadata = scan.scan_saving

    bm02_xrpd_processor.enable_empty_cell_subtraction(setup_globals.difflab6)
    bm02_xrpd_processor.set_cell_pattern_url(
        sample=scan_metadata.sample_name,
        dataset=scan_metadata.dataset,
        scan_number=scan.scan_info["scan_nb"],
        detector="difflab6",
    )

    _scan(expo, npoints)
    testing.wait_workflows(raise_on_error=True)
