"""Recipe "read-object": an object's latest version and its properties as typed values.

Usage: python recipes/read_object.py [object ID, default 437] [object type, default 0 (document)]
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from mfiles_client import run  # noqa: E402
from mfiles_values import obj_id  # noqa: E402
from recipe_helpers import connect, describe, format_value, int_arg  # noqa: E402

from mfiles import IRPCObjectOperations_pb2, IRPCObjectOperations_pb2_grpc  # noqa: E402
from mfiles import IRPCPropertyDefs_pb2, IRPCPropertyDefs_pb2_grpc  # noqa: E402


def main() -> None:
    item_id = int_arg(0, 437)
    object_type = int_arg(1, 0)
    with connect() as client:
        # [START read-object]
        # Property names, by ID. A real application caches these (they change rarely).
        property_defs = client.stub(IRPCPropertyDefs_pb2_grpc.IRPCPropertyDefsStub)
        names = {p.id: p.name for p in property_defs.GetPropertyDefs(
            IRPCPropertyDefs_pb2.GetPropertyDefsRequest()).property_defs}

        # The latest version and its properties in one call.
        objects = client.stub(IRPCObjectOperations_pb2_grpc.IRPCObjectOperationsStub)
        response = objects.GetObjectInfoAndProperties(
            IRPCObjectOperations_pb2.GetObjectInfoAndPropertiesRequest(
                obj_id=obj_id(object_type, item_id),
                latest_version=True))

        print(describe(response.object_info))
        for prop in response.property_array:
            name = names.get(prop.property_def, "?")
            print(f"  {name} ({prop.property_def}): {format_value(prop.value)}")
        # [END read-object]


if __name__ == "__main__":
    run(main)
