import os
import sys

from orionclient.session import APISession
from orionclient.types import ShardCollection

# APISession uses the default profile, or the profile name defined in
# the ORION_PROFILE environment variable.
session = APISession

# a collection can be retrieved directly by id
# collection = session.get_resource(ShardCollection, collection_id)

# retrieving a shard by id is a little more complicated
# shard = session.get_resource(Shard(collection=collection), shard_id)
# or
# shard = Shard.from_msg({"id": shard_id, "collection": collection_id}, session=APISession)
# session.refresh_resource(shard)

collection = None

# find a collection by name
# note that names are not guaranteed to be unique
for c in session.list_resources(ShardCollection):
    if c.name == "Descriptive name of new shard collection":
        collection = c
        break

if collection is None:
    print("Unable to find a collection to delete")
    sys.exit()

for shard in collection.list_shards():
    filename = "collection_{}_{}_shard_{}".format(
        collection.name, collection.id, shard.id
    )
    shard.download_to_file(filename)

    # a shard's data can also be streamed
    bytes_read = 0
    for chunk in shard.download():
        bytes_read += len(chunk)
        print("file '{}' bytes_read={}".format(filename, bytes_read))

    os.remove(filename)

# delete a collection of shards
if session.delete_resource(collection):
    print("collection '{}' deleted".format(collection.name))
