# Convert element selections to components.
# Caution - can go wrong if there are node selections in the model.
# Copyright and related rights waived via CC0.

assert mw.version() >= 17, "Wrong Mecway version"

mw.new_material(name="STEEL")
mw.set_material_type("STEEL", "mechanical", "Isotropic")
mw.set_material_property("STEEL", "youngsmodulus", 205000000000.0)
mw.set_material_property("STEEL", "poissonratio", 0.29)

N=1

for name in mw.named_selections():
    contents = mw.named_selection(name)
    component_name = "COMPONENT_" + str(N).zfill(2)
    # Check if it possibly contains element IDs.
    # Can have false positives for node selections.
    is_elements = True
    number_of_elements = len(mw.all_elements())
    for thingId in contents:
        if isinstance(thingId, FaceId):
            is_elements = False
        elif thingId > number_of_elements:
            is_elements = False

    # Create the component
    if is_elements:
        component_name = mw.new_component(component_name)
        mw.set_material(component_name, "STEEL")
        for element_id in contents:
            mw.set_element_component(element_id, component_name)
        mw.delete_named_selection(name)
        N=N+1


mw.delete_component("Component")
