#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

sys.path.insert(1,fhome+'/software/src/orthancInterface')
import orthancInterface
import orthancDatabaseBrowser


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

db=labkeyDatabaseBrowser.labkeyDB(net)

#by default uses .labkey/Remote.json configuration

oNet=orthancInterface.orthancInterface()
#orthanc only looks at orthanc part of the configuration, so it is the same file
oNet.init(fhome+'/.labkey/network.json')
oDb=orthancDatabaseBrowser.orthancDB(oNet)


dicomBase='/data/dicom/database/dicom'
project='IPNUMMretro/Study'
ds=db.selectRows(project,'lists','imageList',{})


storescu='storescu'
peer='onko-nix.onko-i.si'#this is actually localhost
port='11112'#this is for orthanc

i=0
for row in ds['rows']:
    if row['statusflag']=='ORTHANC':
        continue
    
    if row['file']=='dump.txt':
        row['statusflag']='DUMP'
        db.modifyRows('update',project,'lists','imageList',[row])
        continue
    
    print("ID: {}".format(row['patientid']))
    f=os.path.join(dicomBase,row['study'],row['series'],row['file'])

    print("Instance: {} ".format(f))
    #add files to orthanc via PACS
    try:
        outText=subprocess.check_output([storescu,peer,port,f])
    
    except subprocess.CalledProcessError:
        jsonStatus=oDb.upload(f)
        

    #check if the file made it to orthanc
    qfilter={}
    qfilter['SOPInstanceUID']=row['file']
    rsp=oDb.selectRows(qfilter)

    if len(rsp):
        print("OK")
        row['statusflag']='ORTHANC'
    else:
        print("Failed")

    #update labkey database
    db.modifyRows('update',project,'lists','imageList',[row])
    if i==-1:
        break
    i=i+1

   
print("Done")
quit()

