import logging

from ..model import PyMcaXrfConfiguration

logger = logging.getLogger(__name__)


def ensure_matrix(configuration: PyMcaXrfConfiguration) -> None:
    attenuators = configuration.attenuator_views
    matrix = attenuators["Matrix"]

    if matrix.material.upper() == "MULTILAYER":
        multilayer = configuration.multilayer_views
        matrix_defined = False
        for layer in multilayer.values():
            if layer.use and layer.material:
                matrix_defined = True
                break
    else:
        matrix_defined = bool(matrix.material)

    if matrix.enabled and matrix_defined:
        return

    matrix.enabled = 1
    matrix.material = "H1"
    matrix.density = 1.0
    matrix.thickness = 0.0
    logger.warning(
        "PyMca configuration: matrix is required but not defined. Use dummy matrix with composition 'H1', density 1.0 g/cm^3 and thickness 0.0 cm."
    )
