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):
    return {
        "value": quantity_snapshot(obj.DFlux),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus("DFlux")],
        "editorMode": [str(item) for item in obj.getEditorMode("DFlux")],
        "constraintType": str(obj.ConstraintType),
        "ambientTemp": quantity_snapshot(obj.AmbientTemp),
        "filmCoef": quantity_snapshot(obj.FilmCoef),
        "emissivity": round(float(obj.Emissivity), 9),
        "enableAmplitude": bool(obj.EnableAmplitude),
        "amplitudeValues": list(obj.AmplitudeValues),
        "scale": round(float(obj.Scale), 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("PropertyHeatFluxMutation")
    try:
        obj = document.addObject("Fem::ConstraintHeatflux", "HeatFluxProbe")
        obj.DFlux = "0 W/m^2"
        initial_recompute = int(document.recompute())
        before = semantic_snapshot(obj)
        objects_before = object_snapshot(document)

        obj.DFlux = "500 W/m^2"
        touched_after_edit = {"value": quantity_snapshot(obj.DFlux), "objectState": [str(item) for item in obj.State], "mustExecute": bool(obj.MustExecute)}
        edit_recompute = int(document.recompute())
        edited = semantic_snapshot(obj)

        obj.DFlux = "0 W/m^2"
        touched_after_restore = {"value": quantity_snapshot(obj.DFlux), "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):
            keys = ["constraintType", "ambientTemp", "filmCoef", "emissivity", "enableAmplitude", "amplitudeValues", "scale", "propertyNames"]
            return {key: snapshot[key] for key in keys}

        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-heatflux-mutation",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "DFlux", "typeId": obj.getTypeIdOfProperty("DFlux")},
            "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_HEATFLUX_MUTATION_RESULT=" + json.dumps(run(), sort_keys=True))

