import json

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
CASES = [
    ("default", None),
    ("nominal-watt-per-square-meter", "500 W/m^2"),
    ("zero-boundary", "0 W/m^2"),
    ("negative-boundary", "-5 W/m^2"),
    ("kilowatt-per-square-meter", "2 kW/m^2"),
    ("watt-per-square-millimeter", "1 W/mm^2"),
    ("restored", "0 W/m^2"),
]


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("PropertyHeatFluxSuccess")
    try:
        obj = document.addObject("Fem::ConstraintHeatflux", "HeatFluxProbe")
        document.recompute()
        cases = []
        for case_id, requested in CASES:
            if requested is not None:
                obj.DFlux = requested
                document.recompute()
            snapshot = property_snapshot(obj, "DFlux")
            snapshot.update({"id": case_id, "requested": requested})
            cases.append(snapshot)
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-heatflux-success",
            "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"), "group": obj.getGroupOfProperty("DFlux")},
            "cases": cases,
            "diagnostics": {"exception": None, "documentObjectCount": len(document.Objects)},
        }
    finally:
        App.closeDocument(document.Name)


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

