# Upload all subdirectories as folders.
# Upload all jpg images in these directories as large image items.
# TODO: Upload kw18 files as annotations to these images.

import os
import sys
import pdb
import girder_client


def print_usage():
    print("usage:")
    print("python %s serverName local_folder_path girder_folder_id"%sys.argv[0])


if __name__ == '__main__':

    keys = {'lemon':'', \
            'images': ''}
    urls = {'lemon':'http://lemon/api/v1', \
            'images': 'https://images.slide-atlas.org/api/v1'}


    if len(sys.argv) != 4:
        print_usage()
        exit()

    server_name = sys.argv[1]
    folder_path = sys.argv[2]
    folder_id = sys.argv[3]

    if not server_name in keys:
        print("Unknown server %s"%server_name)
        exit()

    gc = girder_client.GirderClient(apiUrl=urls[server_name])
    gc.authenticate('law12019', apiKey=keys[server_name])

    
    for subdir_name in os.listdir(folder_path):
        subdir_path = os.path.join(folder_path, subdir_name)
        if os.path.isdir(subdir_path):
            print(subdir_name)
            resp = gc.get('folder?parentType=folder&parentId=%s&name=%s'%(folder_id, subdir_name))
            if len(resp) > 0:
                subfolder_id = resp[0]['_id']
            else:
                #cg.createFolder(parentId, name, description='', parentType='folder', public=None, reuseExisting=False, metadata=None):
                subfolder = gc.createFolder(folder_id, subdir_name, description="NOAA Fish")
                subfolder_id = subfolder['_id']

            for file_name in os.listdir(subdir_path):
                if os.path.splitext(file_name) == ".jpg":
                    resp = gc.get('item?folderId=%s&name=%s'%(subfolder_id, file_name))
                    if len(resp) > 0:
                        item_id = resp[0]['_id']
                    else:
                        print("  upload %s"%file_name)
                        item = gc.createItem(subfolder_id, file_name, "Fish")
                        item_id = item['_id']
                        girder_image = gc.uploadFileToItem(item_id, \
                                                       os.path.join(subdir_path, file_name))
                        gc.post('item/%s/tiles'%item_id)















