import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
ASSET = os.path.abspath(".cache/freecad/FreeCAD/data/tests/mesh.obj")
ALTERNATE = "/tmp/property-file-alternate.stl"


def snapshot(document, obj):
    recompute_result = bool(document.recompute())
    return {"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()), "recomputeResult": recompute_result, "objectSet": [{"name": candidate.Name, "typeId": candidate.TypeId} for candidate in document.Objects]}


def run():
    document = App.newDocument("PropertyFileMutation")
    try:
        obj = document.addObject("Mesh::Import", "FileProbe")
        obj.FileName = ASSET
        document.recompute()
        before = snapshot(document, obj)
        obj.FileName = ALTERNATE
        edited = snapshot(document, obj)
        obj.FileName = ASSET
        restored = snapshot(document, obj)
        return {"schemaVersion": 1, "status": "pass", "baselineId": "freecad-1.1.1-property-file-mutation", "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")}, "requested": {"before": ASSET, "edited": ALTERNATE, "restored": ASSET}, "phases": {"before": before, "edited": edited, "restored": restored}, "classification": {"valueChanged": before["value"] != edited["value"], "invalidEditedPath": edited["statusString"] == "File does not exist", "restoreExact": restored["value"] == before["value"] and restored["statusString"] == "Valid", "objectSetStable": before["objectSet"] == edited["objectSet"] == restored["objectSet"], "unknownSemanticDrift": False}}
    finally:
        App.closeDocument(document.Name)


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