import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
ASSET = os.path.abspath(".cache/freecad/FreeCAD/data/tests/mesh.obj")


def mesh_snapshot(obj):
    mesh = getattr(obj, "Mesh", None)
    if mesh is None:
        return {"applicable": False}
    try:
        bounds = mesh.BoundBox
        return {
            "applicable": True,
            "facets": len(mesh.Facets),
            "vertices": len(mesh.Points),
            "bounds": [round(float(value), 9) for value in (bounds.XMin, bounds.YMin, bounds.ZMin, bounds.XMax, bounds.YMax, bounds.ZMax)],
            "isEmpty": len(mesh.Facets) == 0,
        }
    except Exception as error:
        return {"applicable": True, "error": str(error)}


def snapshot(document, obj, requested):
    recompute_result = bool(document.recompute())
    return {
        "requested": requested,
        "value": str(obj.FileName),
        "propertyTypeId": obj.getTypeIdOfProperty("FileName"),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus("FileName")],
        "editorMode": [str(item) for item in obj.getEditorMode("FileName")],
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "mustExecute": bool(obj.mustExecute()) if hasattr(obj, "mustExecute") else None,
        "recomputeResult": recompute_result,
        "mesh": mesh_snapshot(obj),
        "objectSet": [{"name": candidate.Name, "typeId": candidate.TypeId} for candidate in document.Objects],
    }


def run():
    document = App.newDocument("PropertyFileSuccess")
    try:
        obj = document.addObject("Mesh::Import", "FileProbe")
        document.recompute()
        phases = {"default": snapshot(document, obj, "")}
        obj.FileName = ASSET
        phases["valid-mesh"] = snapshot(document, obj, ASSET)
        obj.FileName = "mesh-data/Cube.stl"
        phases["relative-path"] = snapshot(document, obj, "mesh-data/Cube.stl")
        obj.FileName = ASSET
        phases["restored"] = snapshot(document, obj, ASSET)
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-file-success",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "propertyType": "App::PropertyFile",
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "FileName", "typeId": obj.getTypeIdOfProperty("FileName"), "group": obj.getGroupOfProperty("FileName")},
            "asset": {"path": ASSET, "exists": os.path.isfile(ASSET), "bytes": os.path.getsize(ASSET) if os.path.isfile(ASSET) else 0},
            "phases": phases,
            "diagnostics": {"exception": None, "documentObjectCount": len(document.Objects)},
        }
    finally:
        App.closeDocument(document.Name)


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