#  Copyright 2026 European Union
#  Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
#  SPDX-License-Identifier: EUPL-1.2
"""Unit tests covering the GlobalsEditor widget.

:Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
:Description: Verify the editor pushes data without triggering signals and that each signal fires when the user updates a widget.
"""

from __future__ import annotations

from typing import List

import pytest

pytest.importorskip('PySide6', reason='PySide6 is required for GUI tests')
from PySide6.QtWidgets import QApplication

from mafw.steering_gui.views.globals_editor import GlobalsEditor

pytestmark = pytest.mark.gui


@pytest.fixture(scope='session')
def qapp() -> QApplication:
    """Ensure a single QApplication instance exists for all GUI tests."""

    app = QApplication.instance()
    if app is None:
        app = QApplication([])
    return app


def test_set_data_blocks_change_signals(qapp: QApplication) -> None:
    """set_data should populate widgets without emitting their change signals."""

    editor = GlobalsEditor()
    events: List[str] = []
    editor.analysis_name_changed.connect(lambda value: events.append(f'name:{value}'))
    editor.description_changed.connect(lambda value: events.append(f'desc:{value}'))
    editor.new_only_changed.connect(lambda value: events.append(f'new_only:{value}'))
    editor.create_standard_tables_changed.connect(lambda value: events.append(f'standard:{value}'))

    editor.set_data('run', 'desc', True, False)
    assert events == []


def test_signals_emit_when_widgets_update(qapp: QApplication) -> None:
    """Changing widgets should emit the related editor signals."""

    editor = GlobalsEditor()
    name_events: List[str] = []
    desc_events: List[str] = []
    new_only_events: List[bool] = []
    create_events: List[bool] = []

    editor.analysis_name_changed.connect(lambda value: name_events.append(value))
    editor.description_changed.connect(lambda value: desc_events.append(value))
    editor.new_only_changed.connect(lambda value: new_only_events.append(value))
    editor.create_standard_tables_changed.connect(lambda value: create_events.append(value))

    editor.analysis_name_edit.setText('run')
    editor.description_edit.setText('desc')
    editor.new_only_checkbox.setChecked(True)
    editor.create_standard_tables_checkbox.setChecked(True)

    assert name_events[-1] == 'run'
    assert desc_events[-1] == 'desc'
    assert new_only_events[-1] is True
    assert create_events[-1] is True
