import dlubal.api.rfem as rfem
import dlubal.api.common as common

def close_and_create_project_by_name(model_name, app):
    model_list = app.get_model_list().model_info
    for model in model_list:
        if model.name == model_name:
            model_guid = model.guid
            app.close_model(model_id=common.ModelId(guid=model_guid), save_changes=False)
            break

    app.create_model(name=model_name)

    # Clean up the model
    app.delete_all_objects()

def close_and_create_project_by_name_rfem(model_name, rfem_app: rfem.Application):
    model_list = rfem_app.get_model_list().model_info
    for model in model_list:
        if model.name == model_name:
            model_guid = model.guid
            rfem_app.close_model(model_id=common.ModelId(guid=model_guid), save_changes=False)
            break

    rfem_app.create_model(name=model_name)

    # Clean up the model
    rfem_app.delete_all_objects()

def calculate_all(rfem_app: rfem.Application) -> common.OperationResult:
    # Perform plausibility check
    plausibility = rfem_app.plausibility_check(
        type=common.PlausibilityCheckType.PLAUSIBILITY_CHECK_CALCULATION,
        skip_warnings=True
    )

    if plausibility.succeeded:
        # Calculate all
        rfem_app.calculate_all(skip_warnings=True)

    return plausibility