<gh_stars>0
from __future__ import print_function
import sys
import os.path
import csv

import os
import requests

from google.cloud import firestore

CLIO_SERVER = 'prod'
VERSION_TAG = 'v0.2.0'
DVID_VERSION = '05e60c'
DATASET = 'AbG'

CLIO_STORES = {
    "prod": "https://clio-store-vwzoicitea-uk.a.run.app",
    "test": "https://clio-test-7fdj77ed7q-uk.a.run.app",
    "local": "http://localhost:8000"
}
CLIO_UPLOAD_URL = f'{CLIO_STORES[CLIO_SERVER]}/v2/json-annotations/{DATASET}/neurons?version=' + VERSION_TAG

db = firestore.Client()
metadata_ref = db.collection('clio_annotations_global').document('metadata')
metadata_snapshot = metadata_ref.get()
metadata = metadata_snapshot.to_dict()
    
metadata['neurons'][DATASET]['head_tag'] = VERSION_TAG
metadata['neurons'][DATASET]['head_uuid'] = DVID_VERSION
if 'tag_to_uuid' not in metadata['neurons'][DATASET]:
    metadata['neurons'][DATASET]['tag_to_uuid'] = {}
metadata['neurons'][DATASET]['tag_to_uuid'][VERSION_TAG] = DVID_VERSION
if 'uuid_to_tag' not in metadata['neurons'][DATASET]:
    metadata['neurons'][DATASET]['uuid_to_tag'] = {}
metadata['neurons'][DATASET]['uuid_to_tag'][DVID_VERSION] = VERSION_TAG
metadata_ref.set(metadata)

dataset_ref = db.collection('clio_datasets').document(DATASET)
dataset_snapshot = dataset_ref.get()
dataset = dataset_snapshot.to_dict()
dataset['tag'] = VERSION_TAG
dataset['uuid'] = DVID_VERSION
dataset_ref.set(dataset)

try:
    user_token = os.popen("gcloud auth print-identity-token").read().rstrip()
except:
    print(f"Unable to get identity token from gcloud.  Is it installed?")
    sys.exit(1)

def upload_annotations(annotations):
    print(f"annotations to upload: {annotations}")
    r = requests.post(CLIO_UPLOAD_URL, json = annotations, headers = {'Authorization': f'Bearer {user_token}'})
    if r.status_code != 200:
        print(f"Error in POST annotations: {r.status_code}: {r.content}")

# def upload_class_changes():
#     bodyids = [13182, 17319, 17905]
#     batch = []
#     for bodyid in bodyids:
#         batch.append({
#             "bodyid": bodyid,
#             "class": "Motor neuron"
#         })
#     upload_annotations(batch)

def main():

    # Read file of body statuses and post annotations
    BATCH_SIZE = 100
    batch = []
    sent = 0
    with open(f'data/FAbG-anchors.csv') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            if row[0] == "body":
                continue
            bodyid = int(row[0])
            batch.append({
                "bodyid": bodyid,
                "status": "Ancchor"
            })
            if len(batch) == BATCH_SIZE:
                upload_annotations(batch)
                sent += len(batch)
                batch.clear()
                print(f"Sent {sent} status changes...")
    if len(batch) != 0:
        upload_annotations(batch)
        sent += len(batch)
        print(f"Sent {sent} status changes...")


if __name__ == '__main__':
    main()
