import json

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"


def quantity_snapshot(value):
    return {"raw": str(value), "numeric": round(float(value.Value), 9), "unit": str(value.Unit)}


def semantic_snapshot(obj):
    direction = obj.DirectionVector
    return {
        "value": quantity_snapshot(obj.Force),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus("Force")],
        "editorMode": [str(item) for item in obj.getEditorMode("Force")],
        "reversed": bool(obj.Reversed),
        "enableAmplitude": bool(obj.EnableAmplitude),
        "amplitudeValues": list(obj.AmplitudeValues),
        "directionVector": [round(float(direction.x), 9), round(float(direction.y), 9), round(float(direction.z), 9)],
        "propertyNames": list(obj.PropertiesList),
        "shape": {"applicable": hasattr(obj, "Shape")},
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "mustExecute": bool(obj.MustExecute),
    }


def object_snapshot(document):
    return [{"name": obj.Name, "typeId": obj.TypeId} for obj in document.Objects]


def run():
    document = App.newDocument("PropertyForceMutation")
    try:
        obj = document.addObject("Fem::ConstraintForce", "ForceProbe")
        obj.Force = "0 N"
        initial_recompute = int(document.recompute())
        before = semantic_snapshot(obj)
        objects_before = object_snapshot(document)

        obj.Force = "500 N"
        touched_after_edit = {
            "value": quantity_snapshot(obj.Force),
            "objectState": [str(item) for item in obj.State],
            "mustExecute": bool(obj.MustExecute),
        }
        edit_recompute = int(document.recompute())
        edited = semantic_snapshot(obj)

        obj.Force = "0 N"
        touched_after_restore = {
            "value": quantity_snapshot(obj.Force),
            "objectState": [str(item) for item in obj.State],
            "mustExecute": bool(obj.MustExecute),
        }
        restore_recompute = int(document.recompute())
        restored = semantic_snapshot(obj)
        objects_restored = object_snapshot(document)

        def neighbors(snapshot):
            return {key: snapshot[key] for key in ["reversed", "enableAmplitude", "amplitudeValues", "directionVector", "propertyNames"]}

        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-force-mutation",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "Force", "typeId": obj.getTypeIdOfProperty("Force")},
            "recompute": {"initial": initial_recompute, "edit": edit_recompute, "restore": restore_recompute},
            "touchedAfterEdit": touched_after_edit,
            "touchedAfterRestore": touched_after_restore,
            "before": before,
            "edited": edited,
            "restored": restored,
            "neighbors": {"before": neighbors(before), "edited": neighbors(edited), "restored": neighbors(restored), "preserved": neighbors(before) == neighbors(edited) == neighbors(restored)},
            "document": {"objectsBefore": objects_before, "objectsRestored": objects_restored, "objectsPreserved": objects_before == objects_restored},
            "classification": {
                "propertyChanged": before["value"] != edited["value"],
                "propertyRestored": before["value"] == restored["value"],
                "semanticStateRestored": before == restored,
                "neighborPropertiesPreserved": neighbors(before) == neighbors(edited) == neighbors(restored),
                "geometry": "not-applicable-no-shape-property",
            },
        }
    finally:
        App.closeDocument(document.Name)


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