import json
import os

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 property_snapshot(obj, property_name):
    return {
        "name": property_name,
        "typeId": obj.getTypeIdOfProperty(property_name),
        "value": quantity_snapshot(getattr(obj, property_name)),
        "status": [str(item) for item in obj.getPropertyStatus(property_name)],
        "editorMode": [str(item) for item in obj.getEditorMode(property_name)],
    }


def object_snapshot(document):
    force = document.getObject("ForceProbe")
    rigid = document.getObject("RigidForceProbe")
    return {
        "objectSet": [{"name": item.Name, "typeId": item.TypeId} for item in document.Objects],
        "force": {
            "name": force.Name,
            "typeId": force.TypeId,
            "property": property_snapshot(force, "Force"),
            "shape": {"applicable": hasattr(force, "Shape")},
            "state": [str(item) for item in force.State],
            "statusString": str(force.getStatusString()),
        },
        "rigid": {
            "name": rigid.Name,
            "typeId": rigid.TypeId,
            "outputs": [property_snapshot(rigid, name) for name in ["ForceX", "ForceY", "ForceZ"]],
            "shape": {"applicable": hasattr(rigid, "Shape")},
            "state": [str(item) for item in rigid.State],
            "statusString": str(rigid.getStatusString()),
        },
    }


def create_native(path):
    document = App.newDocument("PropertyForceRoundtrip")
    try:
        force = document.addObject("Fem::ConstraintForce", "ForceProbe")
        force.Force = "0 N"
        document.addObject("Fem::ConstraintRigidBody", "RigidForceProbe")
        document.recompute()
        document.saveAs(path)
    finally:
        App.closeDocument(document.Name)
    reopened = App.openDocument(path)
    try:
        reopened.recompute()
        return object_snapshot(reopened)
    finally:
        App.closeDocument(reopened.Name)


def verify_native(path, resaved_path):
    document = App.openDocument(path)
    try:
        document.recompute()
        reopened = object_snapshot(document)
        document.saveAs(resaved_path)
    finally:
        App.closeDocument(document.Name)
    resaved_document = App.openDocument(resaved_path)
    try:
        resaved_document.recompute()
        resaved = object_snapshot(resaved_document)
    finally:
        App.closeDocument(resaved_document.Name)
    return {"reopened": reopened, "resaved": resaved}


mode = os.environ.get("FREECAD_PROPERTY_FORCE_ROUNDTRIP_MODE", "")
path = os.environ.get("FREECAD_PROPERTY_FORCE_ROUNDTRIP_PATH", "")
resaved_path = os.environ.get("FREECAD_PROPERTY_FORCE_ROUNDTRIP_RESAVED_PATH", "")
if mode == "create":
    result = create_native(path)
elif mode == "verify":
    result = verify_native(path, resaved_path)
else:
    raise RuntimeError("FREECAD_PROPERTY_FORCE_ROUNDTRIP_MODE must be create or verify")

print("FREECAD_PROPERTY_FORCE_ROUNDTRIP_RESULT=" + json.dumps({
    "schemaVersion": 1,
    "status": "pass",
    "baselineId": "freecad-1.1.1-property-force-roundtrip",
    "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
    "gitCommit": FREECAD_COMMIT,
    "mode": mode,
    "result": result,
}, sort_keys=True))
