import hashlib
import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"


def vector_value(obj):
    value = obj.Normal
    return {"x": float(value.x), "y": float(value.y), "z": float(value.z)}


def shape_snapshot(obj):
    shape = obj.Shape
    bounds = shape.BoundBox
    return {
        "isNull": bool(shape.isNull()),
        "valid": bool(shape.isValid()),
        "shapeType": shape.ShapeType,
        "solids": len(shape.Solids),
        "faces": len(shape.Faces),
        "edges": len(shape.Edges),
        "vertices": len(shape.Vertexes),
        "area": round(float(shape.Area), 9),
        "volume": round(float(shape.Volume), 9),
        "bounds": [round(float(value), 9) for value in (bounds.XMin, bounds.YMin, bounds.ZMin, bounds.XMax, bounds.YMax, bounds.ZMax)],
        "brepSha256": hashlib.sha256(shape.exportBrepToString().encode("utf-8")).hexdigest(),
    }


def object_snapshot(document):
    obj = document.getObject("DirectionMirror")
    return {
        "objectSet": [{"name": item.Name, "typeId": item.TypeId} for item in document.Objects],
        "object": {
            "name": obj.Name,
            "typeId": obj.TypeId,
            "propertyTypeId": obj.getTypeIdOfProperty("Normal"),
            "value": vector_value(obj),
            "propertyStatus": [str(item) for item in obj.getPropertyStatus("Normal")],
            "editorMode": [str(item) for item in obj.getEditorMode("Normal")],
            "state": [str(item) for item in obj.State],
            "statusString": str(obj.getStatusString()),
            "shape": shape_snapshot(obj),
        },
    }


def create_native(path):
    document = App.newDocument("PropertyDirectionRoundtrip")
    try:
        source = document.addObject("Part::Box", "MirrorSource")
        source.Length = 2
        source.Width = 3
        source.Height = 4
        obj = document.addObject("Part::Mirroring", "DirectionMirror")
        obj.Source = source
        obj.Base = App.Vector(0, 0, 0)
        obj.Normal = App.Vector(0, 0, 1)
        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_DIRECTION_ROUNDTRIP_MODE", "")
path = os.environ.get("FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_PATH", "")
resaved_path = os.environ.get("FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_RESAVED_PATH", "")
if mode == "create":
    result = create_native(path)
elif mode == "verify":
    result = verify_native(path, resaved_path)
else:
    raise RuntimeError("FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_MODE must be create or verify")

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