"""Quickstart: connect, log in, list the 10 most recently modified documents, log out.

Usage: python quickstart.py   (configure with the MFILES_* environment variables; see README.md)
"""

# [START quickstart]
from mfiles_client import MFilesClient, run  # Also makes the stubs in gen/ importable.
from mfiles_values import is_not_deleted, is_object_type

from mfiles import IRPCSearch_pb2, IRPCSearch_pb2_grpc
from mfiles import enums_pb2 as enums
from mfiles import structs_pb2 as structs


def main() -> None:
    # Connect and log in with the MFILES_* settings. Leaving the block logs out.
    with MFilesClient.from_env("M-Files gRPC quickstart") as client:
        request = IRPCSearch_pb2.SearchObjectsRequest(
            # Documents (object type 0) that are not deleted.
            conditions=[structs.SearchConditionArray(
                value=[is_object_type(0), is_not_deleted()])],
            # Newest first by property 21, "Last modified". The server sorts, then takes 10.
            sorting=structs.SearchResultsSorting(rules=structs.SortRuleValueArray(values=[
                structs.SortRule(key=21, options=enums.SortRuleFlags(sort_descending=True))])),
            limit=10)

        # Service stubs run on the client's channel, which adds the session to each call.
        search = client.stub(IRPCSearch_pb2_grpc.IRPCSearchStub)
        response = search.SearchObjects(request)

        for item in response.results:
            version = item.object.version_info
            print(f"{version.title} (ID {item.object.object_info.obj_id.item_id.internal_id}, "
                  f"version {version.version.internal_version}, "
                  f"modified {version.last_modified_at_utc.ToDatetime():%Y-%m-%d %H:%M:%S} UTC)")


if __name__ == "__main__":
    run(main)
# [END quickstart]
