#a script to modify a patient from list. Current implementation deletes 
#all data for patients identified by study regulatory number from study

regulatoryNumber="X000"


#basic python
import os
import subprocess
import re
import datetime
import sys


fhome=os.path.expanduser('~')

sys.path.insert(1,fhome+'/software/src/labkeyInterface')
import labkeyInterface
import labkeyDatabaseBrowser


net=labkeyInterface.labkeyInterface()
net.init(fhome+'/.labkey/network.json')

db=labkeyDatabaseBrowser.labkeyDB(net)

#by default uses .labkey/Remote.json configuration

project="IPNUMMprospektiva/Study"



#study section ################



#select patients enroled under regulatory number
filters=[]
regulatoryFilter={\
    'variable':'regulatoryNumber',\
    'value':regulatoryNumber,\
    'oper':'eq'}
filters.append(regulatoryFilter)

ds=db.selectRows(project,"study","demographicData",filters)

ids=[row['ParticipantId'] for row in ds['rows']]
idCode=""
for id in ids:
    if len(idCode)>0:
        idCode+=";"
    idCode+=id

idFilter={\
    'variable':'ParticipantId',\
    'value':idCode,\
    'oper':'in'}

#print("idCode: {}".format(idCode))

dsts=db.selectRows(project,"study","Datasets",[])


for row in dsts['rows']:

    dsId=db.selectRows(project,"study",row['Name'],[idFilter])
    rows=[r for r in dsId['rows']]
    print("[{}]: {}".format(row['Name'],len(rows)))
    if len(rows)==0:
        continue
    #this is for security only
    #db.modifyRows('delete',project,"study",row['Name'],rows)



# list section ########################


ds=db.selectRows(project,"lists","crfEntry",[regulatoryFilter])
masterRows=[row for row in ds['rows']]

crfs=[row['entryId'] for row in masterRows]

crfCode=""
for crf in crfs:
    if len(crfCode)>0:
        crfCode+=";"
    crfCode+=crf
print("crfCode: {}".format(crfCode))


crfFilter={\
    'variable':'crfRef',\
    'value':crfCode,\
    'oper':'in'}

dsts=db.selectRows(project,"lists","inputLists",[])

for row in dsts['rows']:

    dsId=db.selectRows(project,"lists",row['queryName'],[crfFilter])
    rows=[r for r in dsId['rows']]
    print("[{}]: {}".format(row['queryName'],len(rows)))
    if len(rows)==0:
        continue
    #this is for security only
    #db.modifyRows('delete',project,"lists",row['queryName'],rows)


#this is for security only
#ds=db.modifyRows('delete',project,"lists","crfEntry",masterRows)

print("Done")
quit()

