import os
import sys
import json
import pathlib

def main(configFile):
    with open(configFile) as f:
        config=json.load(f)

    fsetup=os.path.join(os.path.expanduser('~'),'.labkey','setup.json')
    with open(fsetup) as f:
        setup=json.load(f)

    sys.path.append(setup['paths']['labkeyInterface'])
    import labkeyInterface
    import labkeyFileBrowser

    net=labkeyInterface.labkeyInterface()
    fnet=os.path.join(os.path.expanduser('~'),'.labkey','network.json')
    net.init(fnet)

    fb=labkeyFileBrowser.labkeyFileBrowser(net)
    
    [files]=readPatient(fb,config['localDir'],config['project'],config['PatientId'])


def readPatient(fb,localDir,project,patientId):

    rDir=fb.formatPathURL(project,'/'.join([patientId]))
    lDir=os.path.join(localDir,patientId)
    if not os.path.isdir(lDir):
        os.makedirs(lDir)

    ok,files=fb.listRemoteDir(rDir)
    locFiles=[]
    for f in files:
        print(f)
        p=pathlib.Path(f)
        localFile=os.path.join(lDir,p.name)
        fb.readFileToFile(f,localFile)
        locFiles.append(localFile)
    print('Done')
    return locFiles

if __name__=='__main__':
    main(sys.argv[1])