from deriva.core import DerivaServer, get_credential, ErmrestCatalogMutationError

"""
Explanation: Deriva Ermrest Catalog Snapshot Examples
This notebook gives examples of connecting to ERMrest versioned catalogs.
End of explanation
"""


scheme = 'https'
hostname = 'synapse-dev.isrd.isi.edu'
catalog_number = 1

"""
Explanation: Fill in your desired scheme, hostname and catalog number.
End of explanation
"""


credential = get_credential(hostname)

"""
Explanation: Use DERIVA-Auth to get a credential or use None if your catalog allows anonymous access.
End of explanation
"""


server = DerivaServer(scheme, hostname, credential)

"""
Explanation: Get a handle representing your server.
End of explanation
"""


catalog = server.connect_ermrest(catalog_number)
pb = catalog.getPathBuilder()
list(pb.schemas)

"""
Explanation: Connect to a catalog (unversioned)
Connect to a catalog, and list its schemas.
End of explanation
"""


latest = catalog.latest_snapshot()
pb = latest.getPathBuilder()
list(pb.schemas)

"""
Explanation: Get latest snapshot
The current catalog handle can return a handle to the latest snapshot.
End of explanation
"""


print(latest.snaptime)

"""
Explanation: Print the snaptime of this catalog snapshot.
End of explanation
"""


snapshot = server.connect_ermrest('1', '2PM-DGYP-56Z4')
pb = snapshot.getPathBuilder()
list(pb.schemas)

"""
Explanation: Connect to a catalog snapshot
Here we pass the snaptime parameter explicitly in the connect_ermrest method.
End of explanation
"""


snapshot = server.connect_ermrest('1@2PM-DGYP-56Z4')
pb = snapshot.getPathBuilder()
list(pb.schemas)

"""
Explanation: Alternatively, we could pass a "versioned" catalog_id to the connect_ermrest method.
End of explanation
"""


subject = pb.schemas['Zebrafish'].tables['Subject']
print(subject.uri)

"""
Explanation: Finally, we can poke around at schemas and tables as they existed at the specified snaptime.
End of explanation
"""


e = subject.entities()
len(e)

"""
Explanation: Data may be read from the snapshot. Here, we will see how many subjects existed at that point in time.
End of explanation
"""


try:
    subject.insert([{'foo': 'bar'}])
except ErmrestCatalogMutationError as e:
    print(e)

"""
Explanation: However, mutation operations on a catalog snapshot are disabled.
End of explanation
"""


