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
imageDataset='Imaging1'

ds=db.selectRows(project,'study',imageDataset,[])
imageSelector=["CT","PETWB"];

outputBase='/data/dicom/anonymous'
labkeyBase='/data/labkey'
#for links
projectAnonymousBase=os.path.join(labkeyBase,'files',project,'@files/anonymous')


#selected dicom fields
dsFields=db.selectRows(project,'lists','dicomFields',[])
try:
    fields=[r['dicomTagName'] for r in dsFields['rows']]
except KeyError:
    fields=[r['dicomtagname'] for r in dsFields['rows']]

i=0
uid=loadDicom.uuid()




for row in ds["rows"]:
    #link dicoms with a common studiyID
    studyUID=uid.generateStudyUUID('volume')

    for im in imageSelector:
        linkField=im+"2"
        print("Checking row[{}]={}".format(linkField,row[linkField]))
        if row[linkField]=="[DICOM]":
            print("Skipping {}".format(im))
            continue

        seriesId=row[im];
        if seriesId=="0":
            continue
        if seriesId==None:
            continue

        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)

        anonymousDir=os.path.join(tempBase,seriesId+'-a')
        try: 
            os.mkdir(anonymousDir)
        except FileExistsError:
            shutil.rmtree(anonymousDir)
            os.mkdir(anonymousDir)

        patientID="XXXXXX"
        loadDicom.writeAnonymousSeries(slices,anonymousDir,patientID, studyUID,fields)
        anonymousZip=os.path.join(outputBase,seriesId+".zip")
        try:
            outTxt=subprocess.check_output(["zip","-rj",anonymousZip,anonymousDir])
        except subprocess.CalledProcessError:
            print("zip failed for {}, dir {}".format(anonymousZip,anonymousDir))
            
        shutil.rmtree(unzipDir)
        shutil.rmtree(anonymousDir)
        os.remove(fname)
        labkeyAnonymousZip=os.path.join(projectAnonymousBase,seriesId+'.zip')
        try:
            os.symlink(anonymousZip,labkeyAnonymousZip)
        except FileExistsError:
            pass
        row[linkField]="[DICOM]"
       
    db.modifyRows("update",project,"study",imageDataset,[row])
    if i==-1:
        break
    i=i+1

print("Done")
