import os
import json
import re
import subprocess
import shutil
import sys
import numpy
import pydicom
import copy

shome=os.path.expanduser('~nixUser')
sys.path.insert(1,shome+'/software/src/labkeyInterface')
import labkeyInterface
import labkeyDatabaseBrowser


fhome=os.path.expanduser('~')
fconfig=os.path.join(fhome,'.labkey','network.json')
net=labkeyInterface.labkeyInterface()
net.init(fconfig)
db=labkeyDatabaseBrowser.labkeyDB(net)


#also need merlin credentials

fconfigMerlin=os.path.join(fhome,'.labkey','merlin.json')
netMerlin=labkeyInterface.labkeyInterface()
netMerlin.init(fconfigMerlin)
dbMerlin=labkeyDatabaseBrowser.labkeyDB(netMerlin)



project='iPNUMMretro/Study'
merlinProject=project
#project='Orthanc/Database'


anonymousDataset='AnonymousClinicalData'
merlinDataset='ClinicalData'

#getNixID
studyData=db.selectRows(project,'study','Study',[])
nixID=studyData['rows'][0]['nixID']

ds=db.selectRows(project,'study',anonymousDataset,[])

for row in ds['rows']:
    outRow=copy.deepcopy(row)
    outRow['PatientId']='{}-{}'.format(nixID,row['PatientId'])
    dbMerlin.modifyRows('insert',merlinProject,'study',merlinDataset,[outRow])

print('Done')

