import os
import json
import re
import subprocess
import nibabel
import shutil
import sys

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

sys.path.insert(1,shome+'/software/src/orthancInterface')
import orthancInterface
import orthancFileBrowser

sys.path.insert(1,shome+'/software/src/IPNUMM/dicomUtils')
import loadDicom


fhome=os.path.expanduser('~')
fconfig=os.path.join(fhome,'.labkey','network.json')

net=labkeyInterface.labkeyInterface()
net.init(fconfig)
db=labkeyDatabaseBrowser.labkeyDB(net)


onet=orthancInterface.orthancInterface()
onet.init(fconfig)
ofb=orthancFileBrowser.orthancFileBrowser(onet)

hi=0
project='iPNUMMretro/Study'
#project='Orthanc/Database'

tempBase=os.path.join(fhome,'temp')

#all images from database
ds=db.selectRows(project,'study','Imaging',[])
imageSelector=["CT","PETWB"];

niftiBase='/data/nifti'
labkeyBase='/data1/labkey'
projectNIfTIBase=os.path.join(labkeyBase,'/files/',project,'/@files/nifti')

i=0
for row in ds["rows"]:
    for im in imageSelector:
        seriesId=row[im];
        print("{}: {}".format(im,seriesId))
        fname=os.path.join(tempBase,seriesId+".zip");
        ofb.getZip('series',seriesId,fname)
        unzipDir=os.path.join(tempBase,seriesId)
        try:
            os.mkdir(unzipDir)
        except FileExistsError:
            shutil.rmtree(unzipDir)
        try:
            outTxt=subprocess.check_output(["unzip","-d",unzipDir,"-xj",fname])
        except subprocess.CalledProcessError:
            print("unzip failed for {}".format(fname))
            continue
        slices=loadDicom.load(unzipDir)
        img=loadDicom.convertToNIfTI(slices)
        outNIfTI=os.path.join(niftiBase,seriesId+'.nii.gz')
        nibabel.save(img,outNIfTI) 
        shutil.rmtree(unzipDir)
        os.remove(fname)
        labkeyNIfTI=os.path.join(projectNIfTIBase,seriesId+'.nii.gz')
        try:
            os.symlink(labkeyNIfTI,outNIfTI)
        except FileExistsError:
            pass
        
    if i==0:
        break
    i=i+1

print("Done")
