import slicer
import cardiacSPECT
#must have SlicerElastix extension installed
import Elastix
import slicerNetwork
import os

mirID='2SBMIR'
obrID='2SMobr'

configFile=os.path.join(os.path.expanduser('~'),'.cardiacSPECT','register.json')

dataManager=cardiacSPECT.cardiacSPECTLogic(configFile)
network=slicerNetwork.labkeyURIHandler()

#parseConfig if a different location than default is chosen
#network.parseConfig(remote.json)
#network.initRemote()

dataManager.setURIHandler(network)


dataManager.loadPatient(mirID)
dataManager.loadPatient(obrID)

elastix=Elastix.ElastixLogic()
registrationIndex=12

"""
    index 12 corresponds to:
    ['par0015', '3D CT, monomodal', 'lung',
   'intrapatient; B-spline transformation; several similarity metrics',
   'Staring (2013), Towards Local Progression Estimation of Pulmonary Emphysema using CT',
   ['Parameters.Par0015.expA.patient.NC.affine.txt', 'Parameters.Par0015.expA.patient.NC.bspline.txt']]
 """
RegistrationPresets_ParameterFilenames=5
parameterFilenames = elastix.getRegistrationPresets()[registrationIndex][RegistrationPresets_ParameterFilenames]

fixedVolumeNode=slicer.util.getFirstNodeByName(mirID+'CT')
movingVolumeNode=slicer.util.getFirstNodeByName(obrID+'CT')

transformNodeName=obrID+'_DF'
transformNodeFile=outPath=os.path.join(os.path.expanduser('~'),'temp',transformNodeName+'.h5')
ok, transformNode= slicer.util.loadTransform(transformNodeFile,returnNode=True)
if not ok:
    transformNode=slicer.vtkMRMLTransformNode()
    transformNode.SetName(transformNodeName) # a bspline transform node
    slicer.mrmlScene.AddNode(transformNode)

    elastix.registerVolumes(fixedVolumeNode, movingVolumeNode,
        parameterFilenames = parameterFilenames,
        outputVolumeNode = None,
        outputTransformNode = transformNode,
        fixedVolumeMaskNode = None,
        movingVolumeMaskNode = None,
        #recent elastix version
        forceDisplacementFieldOutputTransform = 1)

    slicer.util.saveNode(transformNode,transformNodeFile)
#already a grid transform node
#gridTransformNode=slicer.modules.transforms.logic().ConvertToGridTransform(transformNode, fixedVolumeNode)

dataManager.applyTransform(obrID,mirID,0,19)
dataManager.storeVolumeNodes(obrID,0,19)
dataManager.storeVolumeNodes(mirID,0,19)
dataManager.storeTransformation(obrID)

quit()
