'''
Exports information about a region of interest defined by the bounds of a
box in the vtk window. We use a vtkBoxWidget, with a strating size of 
20x20x20 mm, and keep later export information about its centre, scaling 
(following resizing) in the x, y and z direction, and rotation about the
centre of the box. This information allows us to create a 3d blob of the
correct scaling and rotation and the specified centre position in the same 
volume in different software. 

Ouput is to a comma separeted ascii text file of any name, with 9 
consecutive floating point numbers:
    x_rotation
    y rotation
    z rotation
    x scaling (relative to initial 20mm size)
    y scaling (relative to initial 20mm size)
    z scaling (relative to initial 20mm size)
    x coordinate of centre
    y coordinate of centre
    z coordinate of centre

The complimentary matlab reader customROI.m exists
'''
import time
import vtk
from numpy import *
import wx
import math





def importROI(MainVTKWindow):
    try: 
	MainVTKWindow.bw
        print 'Alreadty have an ROI loaded / generated .. please start a new session.'
    except AttributeError:
        MainVTKWindow.bw = vtk.vtkBoxWidget()
        MainVTKWindow.bw.SetInteractor(MainVTKWindow.widget)
        MainVTKWindow.bw.SetPriority(1.0)
        MainVTKWindow.bw.SetHandleSize(0.0025)
        MainVTKWindow.bw.SetScalingEnabled(1)
	print 'blah'
	dlg = wx.FileDialog(MainVTKWindow, "Load the ROI file ...", "", "","All Files|*", wx.OPEN)
	if (dlg.ShowModal() == wx.ID_OK):
		MainVTKWindow.fileName = dlg.GetFilename()
		MainVTKWindow.dirName = dlg.GetDirectory()

		f = open(MainVTKWindow.dirName+'/'+MainVTKWindow.fileName)
		
		t = f.read()
		f.close()

		t = t.strip() #remove whitespace
		t = t.split(',') #split into separate numbers
		nums = []
		for i in t:
			nums.append(float(i))


		MainVTKWindow.bw.SetPlaceFactor(1.0)
		MainVTKWindow.bw.PlaceWidget(-10.0,10.0,-10.0,+10.0,-10.0,+10.0)
	    
		MainVTKWindow.bw.On()
		MainVTKWindow.centre_chosen = 1		
		
		xfm = vtk.vtkTransform()
		# don't quite get this .. cant apply a concatenation of transformation
		# details in a single step so have to create one xfm to do rotation &
		# scaling, get ouput from that and then add the translation values 
		# into the compute matrix (?) .. but it works		
		xfm_rot_sc = vtk.vtkTransform()
		xfm_rot_sc.RotateX(nums[0])
		xfm_rot_sc.RotateY(nums[1])
		xfm_rot_sc.RotateZ(nums[2])
		xfm_rot_sc.Scale((nums[3],nums[4],nums[5]))
		xfm_rot_sc.Update()		
	
		xfm_fin_mat = vtk.vtkMatrix4x4()
		xfm_rot_sc.Update()
		xfm_rot_sc.GetMatrix(xfm_fin_mat)
		
		xfm_fin_mat.SetElement(0,3,nums[6])
		xfm_fin_mat.SetElement(0,7,nums[7])
		xfm_fin_mat.SetElement(0,11,nums[8])
		
		xfm_fin = vtk.vtkTransform()
		xfm_fin.SetMatrix(xfm_fin_mat)
		xfm_fin.Update()

		MainVTKWindow.bw.SetTransform(xfm_fin)
		MainVTKWindow.bw.Modified()
		MainVTKWindow.widget.Render()

		print 'Loaded ROI file'

	else:
		print 'Load ROI file cancelled ...'
		dlg.Destroy()



def exportROI(MainVTKWindow):
    
    
    
    try: MainVTKWindow.bw
    except AttributeError:
    
        MainVTKWindow.bw = vtk.vtkBoxWidget()
        MainVTKWindow.bw.SetInteractor(MainVTKWindow.widget)
        MainVTKWindow.bw.SetPriority(1.0)
        MainVTKWindow.bw.SetHandleSize(0.0025)
        MainVTKWindow.bw.SetScalingEnabled(1)
    
        MainVTKWindow.bw.SetPlaceFactor(1.0)
        MainVTKWindow.bw.PlaceWidget(-10.0,10.0,-10.0,10.0,-10.0,10.0)
    
        MainVTKWindow.bw.On()
        MainVTKWindow.centre_chosen = 0
    
    else:
        if MainVTKWindow.centre_chosen == 0:
            pick = MainVTKWindow.widget.GetPicker()
            r = MainVTKWindow.widget.GetEventPosition()
            s = r[0],r[1],0
            pick.Pick(s, MainVTKWindow.ren)
            ppos = pick.GetPickPosition()
            
            my_xfm = vtk.vtkTransform()
            my_xfm.Translate(ppos)
            MainVTKWindow.centre_chosen = 1
        
            MainVTKWindow.bw.SetTransform(my_xfm)
            MainVTKWindow.bw.Modified()
            MainVTKWindow.widget.Render()
        
        else:
            MainVTKWindow.bw.Modified()
            #t = vtk.vtkPolyData()
            #MainVTKWindow.bw.GetPolyData(t)

            dlg = wx.FileDialog(MainVTKWindow, "Save the ROI bounds file as ...", "", "","ROI bounds files(*.mat)|*.mat|All Files|*", wx.SAVE)
            if (dlg.ShowModal() == wx.ID_OK):
                MainVTKWindow.fileName = dlg.GetFilename()
                MainVTKWindow.dirName = dlg.GetDirectory()
                xfm = vtk.vtkTransform()
                MainVTKWindow.bw.GetTransform(xfm)
                ori = xfm.GetOrientation()
                scale = xfm.GetScale()
                pos = xfm.GetPosition()
                output = [ori[0], ori[1], ori[2], scale[0], scale[1], scale[2], pos[0], pos[1], pos[2]]
                f = open(MainVTKWindow.dirName+'/'+MainVTKWindow.fileName, 'a')
                f.write(str(output)[1:-1]) #remove list brackets before writing to csv
                f.write('\n')
                f.close()
                print 'Saved ROI bounds file to '+MainVTKWindow.dirName+'/'+MainVTKWindow.fileName
            else:
                print 'Save ROI bounds file cancelled ...'
            dlg.Destroy()
 



