import json

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"


def object_set(document):
    return [{"name": obj.Name, "typeId": obj.TypeId} for obj in document.Objects]


def snapshot(document, obj):
    document.recompute()
    return {
        "value": str(obj.Font),
        "propertyTypeId": obj.getTypeIdOfProperty("Font"),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus("Font")],
        "editorMode": [str(item) for item in obj.getEditorMode("Font")],
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "objectSet": object_set(document),
    }


def exception_snapshot(callback):
    try:
        callback()
    except Exception as error:
        return {"type": type(error).__name__, "message": str(error)}
    return None


def active_transaction_snapshot():
    active = App.getActiveTransaction()
    if not active:
        return {"name": "", "id": 0}
    return {"name": str(active[0]), "id": int(active[1])}


def run():
    document = App.newDocument("PropertyFontFailure")
    try:
        obj = document.addObject("TechDraw::DrawViewAnnotation", "FontProbe")
        document.recompute()
        document.UndoMode = 1
        initial = snapshot(document, obj)
        before = snapshot(document, obj)
        before_objects = object_set(document)
        wrong_type_exception = exception_snapshot(lambda: setattr(obj, "Font", 12345))
        after = snapshot(document, obj)

        obj.setEditorMode("Font", ["ReadOnly"])
        obj.setPropertyStatus("Font", "Immutable")
        disabled_before = snapshot(document, obj)
        disabled_objects_before = object_set(document)
        disabled_exception = exception_snapshot(lambda: setattr(obj, "Font", "Blocked Font"))
        disabled_after = snapshot(document, obj)
        disabled_objects_after = object_set(document)
        disabled_status = [str(item) for item in obj.getPropertyStatus("Font")]
        disabled_editor_mode = [str(item) for item in obj.getEditorMode("Font")]
        obj.setPropertyStatus("Font", "-Immutable")
        obj.setEditorMode("Font", 0)

        document.openTransaction("property-font-cancel")
        transaction_before = snapshot(document, obj)
        transaction_objects_before = object_set(document)
        obj.Font = "Transaction Font"
        transaction_edited = snapshot(document, obj)
        transaction_pending_after_edit = bool(document.HasPendingTransaction)
        transaction_active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after_abort = snapshot(document, obj)
        transaction_objects_after = object_set(document)
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-font-failure",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "propertyType": "App::PropertyFont",
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "Font", "typeId": obj.getTypeIdOfProperty("Font")},
            "initial": initial,
            "failure": {"id": "wrong-type", "requested": 12345, "exception": wrong_type_exception, "before": before, "after": after, "beforeObjects": before_objects, "afterObjects": object_set(document), "objectsPreserved": before_objects == object_set(document)},
            "disabled": {"classification": "editor-read-only-and-python-immutable", "status": disabled_status, "editorMode": disabled_editor_mode, "exception": disabled_exception, "before": disabled_before, "after": disabled_after, "beforeObjects": disabled_objects_before, "afterObjects": disabled_objects_after, "restoredStatus": [str(item) for item in obj.getPropertyStatus("Font")], "restoredEditorMode": [str(item) for item in obj.getEditorMode("Font")]},
            "transaction": {"before": transaction_before, "edited": transaction_edited, "afterAbort": transaction_after_abort, "objectsBefore": transaction_objects_before, "objectsAfter": transaction_objects_after, "undoMode": int(document.UndoMode), "pendingAfterEdit": transaction_pending_after_edit, "pendingAfterAbort": bool(document.HasPendingTransaction), "activeAfterEdit": transaction_active_after_edit, "activeAfterAbort": active_transaction_snapshot(), "restored": transaction_before == transaction_after_abort, "objectsRestored": transaction_objects_before == transaction_objects_after},
            "cancellationBoundary": {"supported": False, "classification": "synchronous-property-setter", "reason": "no-native-cancel-hook", "replacement": "abort-active-document-transaction"},
            "documentIntegrity": {"initialObjects": initial["objectSet"], "finalObjects": object_set(document), "objectsPreserved": initial["objectSet"] == object_set(document), "objectCount": len(document.Objects)},
        }
    finally:
        App.closeDocument(document.Name)


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