import json

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
CASES = [
    ("default", None),
    ("nominal-newton", "500 N"),
    ("zero-boundary", "0 N"),
    ("negative-boundary", "-5 N"),
    ("kilonewton", "2 kN"),
    ("restored", "0 N"),
]


def value_snapshot(obj, property_name):
    value = getattr(obj, property_name)
    return {
        "raw": str(value),
        "numeric": round(float(value.Value), 9),
        "unit": str(value.Unit),
    }


def property_snapshot(obj, property_name):
    return {
        "objectName": obj.Name,
        "objectTypeId": obj.TypeId,
        "propertyName": property_name,
        "typeId": obj.getTypeIdOfProperty(property_name),
        "group": obj.getGroupOfProperty(property_name),
        "status": [str(item) for item in obj.getPropertyStatus(property_name)],
        "editorMode": [str(item) for item in obj.getEditorMode(property_name)],
        "value": value_snapshot(obj, property_name),
        "shape": {"applicable": hasattr(obj, "Shape")},
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
    }


def run():
    document = App.newDocument("PropertyForceSuccess")
    try:
        force = document.addObject("Fem::ConstraintForce", "ForceProbe")
        rigid = document.addObject("Fem::ConstraintRigidBody", "RigidForceProbe")
        document.recompute()
        cases = []
        for case_id, requested in CASES:
            if requested is not None:
                force.Force = requested
                document.recompute()
            snapshot = property_snapshot(force, "Force")
            snapshot.update({"id": case_id, "requested": requested})
            cases.append(snapshot)
        outputs = [property_snapshot(rigid, name) for name in ["ForceX", "ForceY", "ForceZ"]]
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-force-success",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "object": {"name": force.Name, "typeId": force.TypeId},
            "property": {"name": "Force", "typeId": force.getTypeIdOfProperty("Force"), "group": force.getGroupOfProperty("Force")},
            "cases": cases,
            "outputProperties": outputs,
            "diagnostics": {"exception": None, "documentObjectCount": len(document.Objects)},
        }
    finally:
        App.closeDocument(document.Name)


print("FREECAD_PROPERTY_FORCE_SUCCESS_RESULT=" + json.dumps(run(), sort_keys=True))
