import xml.etree.ElementTree as ET

from epiuclid.serializers.pathway_mapper import IUCLIDSubstanceData

from .base import (
    _sub,
    build_document,
    document_key,
)

NS_SUBSTANCE = "http://iuclid6.echa.europa.eu/namespaces/SUBSTANCE/10.0"
ET.register_namespace("", NS_SUBSTANCE)


class SubstanceBuilder:
    def build(self, data: IUCLIDSubstanceData) -> str:
        substance = ET.Element(f"{{{NS_SUBSTANCE}}}SUBSTANCE")

        _sub(substance, NS_SUBSTANCE, "Templates")
        _sub(substance, NS_SUBSTANCE, "ChemicalName", data.name)

        if data.reference_substance_uuid:
            ref_sub = _sub(substance, NS_SUBSTANCE, "ReferenceSubstance")
            _sub(
                ref_sub,
                NS_SUBSTANCE,
                "ReferenceSubstance",
                document_key(data.reference_substance_uuid),
            )

        doc_key = document_key(data.uuid)
        return build_document(
            document_key=doc_key,
            document_type="SUBSTANCE",
            name=data.name,
            content_element=substance,
        )
