#!/usr/bin/env python
import wx
import sys, os
import time

#from dv3dLoadExternalSurface import *
from dv3dSurfaceFunctions import *
from dv3dContourPlot3D_routines import *
from dv3dMinNormFunctions import *
from dv3dDipoleFunctions import *
from dv3dLoadVTKPolyData import *
from dv3dExportPolyDataToDotVTKFile import *
from dv3dSurfaceIntersectsVolumeData import UseCurrentSurfaceAsDataProbe

#used in some routines as globals
index_to_data, threshold = 0,0



#launch a title logo
class StartupThread ( threading.Thread ):
    def run(self):
        for i in range(10):
            os.system('dir/w')
            time.sleep(1)
            

class ColourSelection(wx.Panel):
    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)

        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent


class Dipole_4DNI_Selection(wx.Panel):
    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)
        
        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent
        #later when we use sliders etc. we can call the index in the vtk
        # object list of the main window if we track it here i.e.
        # we get the newly created object's index and make it a
        # property of this frame (or panel:) )
        self.index_into_objects = len(self.frame_parent.ListOfObjects)-1
        
        self.parent.SetSize(wx.Size(320, 240))


        self.label1 = wx.StaticText(id=-1,
              label=u'Select a 4d-dipole export file', name='label1',
              parent=self, pos=wx.Point(24, 20), style=0)
        
        self.source_text1 = wx.TextCtrl(id=-1, name='Source1',
              parent=self, pos=wx.Point(24, 50), size=wx.Size(150, 20),
              style=wx.TE_RIGHT, value='C:/Documents and Settings/andre/Desktop/DV3D_examples/dipole_file_left_1630ms.dip')
        self.source_text1.SetEditable(0)
        
        self.BrowseBtn1 = wx.Button(id=-1, label='Choose',
              name='BrowseBtn1', parent=self, pos=wx.Point(190, 60)
              , style=0)
        self.BrowseBtn1.Bind(wx.EVT_BUTTON, self.OnBrowseBtn1,
              id=-1)        


        self.label2 = wx.StaticText(id=-1,
              label=u'Select a transformation matrix for the session', name='label2',
              parent=self, pos=wx.Point(24, 90), style=0)
        
        self.source_text2 = wx.TextCtrl(id=-1, name='Source2',
              parent=self, pos=wx.Point(24, 120), size=wx.Size(150, 20),
              style=wx.TE_RIGHT, value='C:/Documents and Settings/andre/Desktop/DV3D_examples/MEG_data_to_structural_transform.txt')
        self.source_text2.SetEditable(0)
        
        self.BrowseBtn2 = wx.Button(id=-1, label='Choose',
              name='BrowseBtn2', parent=self, pos=wx.Point(190, 120)
              , style=0)
        self.BrowseBtn2.Bind(wx.EVT_BUTTON, self.OnBrowseBtn2,
              id=-1)           
    
        self.RunButton = wx.Button(id=-1, label='Load',
              name='RunButton', parent=self, pos=wx.Point(220, 170)
              , style=0)
        self.RunButton.Bind(wx.EVT_BUTTON, self.OnRunButton,
              id=-1)  

    def OnRunButton(self, evt):
        dipole_file = self.source_text1.GetValue()
        transform_file = self.source_text2.GetValue()
        self.parent.Destroy()
        Load_Dipole_4DNI(self.frame_parent, dipole_file, transform_file)
        
    
    
    def OnBrowseBtn1(self, evt):
        dlg = wx.FileDialog(self, "Select a 4d-dipole export file", '', "", "*", wx.OPEN|wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.data_source_path = dlg.GetPath()
            if self.data_source_path != None:
                self.source_text1.SetValue(self.data_source_path)
    
    def OnBrowseBtn2(self, evt):
        dlg = wx.FileDialog(self, "Select a transformation matrix for the session", '', "", "*", wx.OPEN|wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.data_source_path = dlg.GetPath()
            if self.data_source_path != None:
                self.source_text2.SetValue(self.data_source_path)





class MinimumNorm_Type1_Selection(wx.Panel):
    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)
        
        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent
        #later when we use sliders etc. we can call the index in the vtk
        # object list of the main window if we track it here i.e.
        # we get the newly created object's index and make it a
        # property of this frame (or panel:) )
        self.index_into_objects = len(self.frame_parent.ListOfObjects)-1
        
        self.parent.SetSize(wx.Size(320, 240))

        self.label1 = wx.StaticText(id=-1,
              label=u'Select a .vtk structural shape file', name='label1',
              parent=self, pos=wx.Point(24, 20), style=0)
        
        self.source_text1 = wx.TextCtrl(id=-1, name='Source1',
              parent=self, pos=wx.Point(24, 50), size=wx.Size(150, 20),
              style=wx.TE_RIGHT, value='C:/Documents and Settings/andre/Desktop/DV3D_examples/Min_norm_brain_surface.vtk')
        self.source_text1.SetEditable(0)
        
        self.BrowseBtn1 = wx.Button(id=-1, label='Choose',
              name='BrowseBtn1', parent=self, pos=wx.Point(190, 60)
              , style=0)
        self.BrowseBtn1.Bind(wx.EVT_BUTTON, self.OnBrowseBtn1,
              id=-1)        


        self.label2 = wx.StaticText(id=-1,
              label=u'Select a .bin time-series file', name='label2',
              parent=self, pos=wx.Point(24, 90), style=0)
        
        self.source_text2 = wx.TextCtrl(id=-1, name='Source2',
              parent=self, pos=wx.Point(24, 120), size=wx.Size(150, 20),
              style=wx.TE_RIGHT, value='C:/Documents and Settings/andre/Desktop/DV3D_examples/min_norm_timepoint_data.bin')
        self.source_text2.SetEditable(0)
        
        self.BrowseBtn2 = wx.Button(id=-1, label='Choose',
              name='BrowseBtn2', parent=self, pos=wx.Point(190, 120)
              , style=0)
        self.BrowseBtn2.Bind(wx.EVT_BUTTON, self.OnBrowseBtn2,
              id=-1)           
    
        self.RunButton = wx.Button(id=-1, label='Load',
              name='RunButton', parent=self, pos=wx.Point(220, 170)
              , style=0)
        self.RunButton.Bind(wx.EVT_BUTTON, self.OnRunButton,
              id=-1)  
    
    def OnRunButton(self, evt):
        vertex_file = self.source_text1.GetValue()
        time_series_file = self.source_text2.GetValue()
        self.parent.Destroy()
        LoadMinNormType1(self.frame_parent, vertex_file, time_series_file)
        
    
    
    def OnBrowseBtn1(self, evt):
        dlg = wx.FileDialog(self, "Select a .vtk structural shape file", '', "", "*.vtk", wx.OPEN|wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.data_source_path = dlg.GetPath()
            if self.data_source_path != None:
                self.source_text1.SetValue(self.data_source_path)
    
    def OnBrowseBtn2(self, evt):
        dlg = wx.FileDialog(self, "Select a .bin time-series file", '', "", "*.bin", wx.OPEN|wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.data_source_path = dlg.GetPath()
            if self.data_source_path != None:
                self.source_text2.SetValue(self.data_source_path)        


class ContourPlot3D_Selection(wx.Panel):
    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)

        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent
        #later when we use sliders etc. we can call the index in the vtk
        # object list of the main window if we track it here i.e.
        # we get the newly created object's index and make it a
        # property of this frame (or panel:) )
        self.index_into_objects = len(self.frame_parent.ListOfObjects)-1
        
        self.parent.SetSize(wx.Size(430,480))
        
        self.staticText0 = wx.StaticText(id=-1,
              label=u'Select a file', name='staticText0',
              parent=self, pos=wx.Point(24, 10), size=wx.Size(75, 16),
              style=0)
        
        self.source_text = wx.TextCtrl(id=-1, name='Source',
              parent=self, pos=wx.Point(100, 10), size=wx.Size(150, 20),
              style=wx.TE_RIGHT, value='Not selected ...')
        self.source_text.SetEditable(0)
        
        self.BrowseBtn = wx.Button(id=-1, label='Browse',
              name='BrowseBtn', parent=self, pos=wx.Point(290, 10),
              size=wx.Size(91, 23), style=0)
        self.BrowseBtn.Bind(wx.EVT_BUTTON, self.OnBrowseResultsButton,
              id=-1)
        
        self.staticText1 = wx.StaticText(id=-1,
              label=u'Pre-trigger duration (ms)', name='staticText1',
              parent=self, pos=wx.Point(24, 56),
              style=0)

        self.staticText2 = wx.StaticText(id=-1,
              label=u'Epoch length including pre-trigger (ms)',
              name='staticText2', parent=self, pos=wx.Point(24, 88), style=0)

        self.staticText3 = wx.StaticText(id=-1,
              label=u'Trigger values found:', name='staticText3',
              parent=self, pos=wx.Point(24, 120),
              style=0)

        self.staticText4 = wx.StaticText(id=-1,
              label=u'Trigger values to include:', name='staticText4',
              parent=self, pos=wx.Point(24, 208), size=wx.Size(161, 16),
              style=0)

        self.staticText5 = wx.StaticText(id=-1,
              label=u'(separate with a comma e.g. 4096,4122 or type all)',
              name='staticText5', parent=self, pos=wx.Point(34, 232),
              size=wx.Size(340, 16), style=0)

        self.textCtrl1 = wx.TextCtrl(id=-1, name='textCtrl1',
              parent=self, pos=wx.Point(220, 48), size=wx.Size(50, 22),
              style=0, value='')

        self.textCtrl2 = wx.TextCtrl(id=-1, name='textCtrl2',
              parent=self, pos=wx.Point(220, 80), size=wx.Size(50, 22),
              style=0, value='')

        self.textCtrl3 = wx.TextCtrl(id=-1, name='textCtrl3',
              parent=self, pos=wx.Point(24, 144), size=wx.Size(368, 56),
              style=wx.TE_MULTILINE, value=u'')
        self.textCtrl3.SetEditable(False)

        self.textCtrl4 = wx.TextCtrl(id=-1, name='textCtrl4',
              parent=self, pos=wx.Point(24, 256), size=wx.Size(368, 56),
              style=wx.TE_MULTILINE, value=u'')

        self.button1 = wx.Button(id=-1, label=u'Cancel',
              name='button1', parent=self, pos=wx.Point(72, 416),
              size=wx.Size(104, 20), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
              id=-1)

        self.button2 = wx.Button(id=-1, label=u'Submit',
              name='button2', parent=self, pos=wx.Point(256, 416),
              size=wx.Size(104, 20), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
              id=-1)

        self.staticText6 = wx.StaticText(id=-1,
              label=u'Filter range (lowpass,highpass e.g. 2,40) or leave broadband',
              name='staticText6', parent=self, pos=wx.Point(24, 336),
              size=wx.Size(383, 16), style=0)

        self.textCtrl5 = wx.TextCtrl(id=-1, name='textCtrl5',
              parent=self, pos=wx.Point(24, 360), size=wx.Size(256, 22),
              style=0, value='broadband')

    def OnBrowseResultsButton(self, evt):
        dlg = wx.FileDialog(self, "Choose the 4D MEG data file:", '', "", "*", wx.OPEN|wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.data_source_path = dlg.GetPath()
            
            if self.data_source_path != None:
                self.source_text.SetValue(self.data_source_path)
                trigs = Extract_triggers(self.data_source_path)
                self.textCtrl3.SetValue(trigs)
            

    def OnButton1Button(self, event):
        print 'cancelled'
        self.parent.Destroy()

    def OnButton2Button(self, event):
        #Submit the settings
        
        #check if all values have been stipulated
        
        #check pretrig and duration
        try:
            pretrig,duration = int(self.textCtrl1.GetValue()),int(self.textCtrl2.GetValue())
        except:
            dlg = wx.MessageDialog(None,'Please set a pretrigger length and a duration in ms','Error!',wx.OK)
            dlg.ShowModal()
            return

        #check trigger values
        #TODO - add sanity check - are the stipulated values in the list above?
        if self.textCtrl4.GetValue() == 'all' or self.textCtrl4.GetValue() == 'All' or self.textCtrl4.GetValue() == 'ALL':
            pass
        elif self.textCtrl4.GetValue() == '':
            dlg = wx.MessageDialog(None,'Please select at least one trigger value from the list; select multiple and separate with commas; type all to include all trigger values','Error!',wx.OK)
            dlg.ShowModal()
            return
        else:
            pass
        
        #check filter values
        #TODO - add sanity check - are there 2 values supplied, comma separated?
        if self.textCtrl5.GetValue() == 'broadband':
            pass
        elif self.textCtrl5.GetValue() == '':
            dlg = wx.MessageDialog(None,'Please state the filter range you would like to apply. Type 1,30 (comma separated) for 1-30 Hz ... or leave as broadband','Error!',wx.OK)
            dlg.ShowModal()
            return
        else:
            pass
        
        trigger_string = str(self.textCtrl4.GetValue())
        filter_string = str(self.textCtrl5.GetValue())
        filename = self.source_text.GetValue()
        self.parent.Destroy()
        ContourPlot3d(filename, pretrig, duration, trigger_string, filter_string, self.frame_parent)
        


class DialogPickSurfaceForClipper(wx.Panel):
    #allows the user to select one of the loaded volumes to interrogate

    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)
        
        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent
        self.index_to_data = 0
        
        drop_down_content = [] #the list holder for the volume selection
        drop_down_content.append('')
        
        #scan all objects to see if they are cortical surfaces
        
        for j in range(len(self.frame_parent.ListOfObjects)):
            if self.frame_parent.ListOfObjects[j].my_type == i:
                    label = self.frame_parent.ListOfObjects[j].my_label
                    if drop_down_content[-1] == label:
                        pass
                    else:
                        drop_down_content.append(label)

        self.VolumeChoiceLabel = wx.StaticText(id=-1, label='Choose a loaded volume:', name='ChooseVol',
              parent=self, pos=wx.Point(16, 16), style=0)
        
        self.VolumeChoice = wx.Choice(choices=drop_down_content, id=-1,
              name='VolumeChoice', parent=self, pos=wx.Point(16, 42),
              size=wx.Size(250, 21), style=0)
        self.VolumeChoice.Bind(wx.EVT_CHOICE, self.OnVolumeChoice,
              id=-1)
        
        self.DataMax = wx.StaticText(id=-1, label='Data maximum: not selected', name='DataMax',
              parent=self, pos=wx.Point(16, 90), style=0)
        
        self.DataMin = wx.StaticText(id=-1, label='Data minimum: not selected', name='DataMin',
              parent=self, pos=wx.Point(16, 110), style=0)

        self.ExtractionThresholdLabel = wx.StaticText(id=-1, label='Set the extraction threshold:', name='extThrLab',
              parent=self, pos=wx.Point(16, 135), style=0)

        self.ExtractionThreshold = wx.TextCtrl(id=-1, name='ExtractThr',
              parent=self, pos=wx.Point(175, 130), size=wx.Size(75, 20),
              style=wx.TE_RIGHT, value='0')
        self.ExtractionThreshold.SetEditable(1)
        
        self.GenerateSurface = wx.Button(self, -1, 'Run', (250,250))
        self.Bind(wx.EVT_BUTTON, self.OnGenerateSurfaceButton, self.GenerateSurface)

        self.SpreadChkBx = wx.CheckBox(id=-1,
              label='Generate as distribution', name='spreadGen',
              parent=self, pos=wx.Point(16, 170), 
              style=0)
        self.SpreadChkBx.SetValue(False)

    
    def mu(self):
        for i in range(10):
            time.sleep(1)
    
    def OnGenerateSurfaceButton(self, evt):
        ind = self.index_to_data
        data_vol = self.frame_parent.my_loaded_volumes[ind][0].volume_data
        data_source_path = self.frame_parent.my_loaded_volumes[ind][0].data_source_path
        thr = self.ExtractionThreshold.GetValue()
        thr = thr.split(',')
        
        if self.SpreadChkBx.GetValue() == True:
            # if the usr wants to view the distribution of the activation
            #  we create a table of colour and transparencies to assign
            #  to aid this
            if len(thr) > 1:
                my_colours = []
                for i in range(len(thr)):
                    my_tint = float(i*(1/float(len(thr))))                    
                    my_colours.append((1.0, my_tint, 0,))
                    self.parent.Destroy()
                    Generate_surface_from_loaded_volume(thr[i], data_vol, self.frame_parent, self.frame_parent.tmp_data_max, data_source_path, my_colours[i], my_tint)
            
        
        else:
            self.parent.Destroy()
            #threading.Thread(self.mu())            
            for i in range(len(thr)):
                #loop through multiple surfaces if provided
                Generate_surface_from_loaded_volume(thr[0], data_vol, self.frame_parent, self.frame_parent.tmp_data_max, data_source_path, (1.0, 1.0, 0))
        
        
    def OnVolumeChoice(self, evt):
        choice = self.VolumeChoice.GetStringSelection()

        if choice == 'Base volume':
            self.frame_parent.tmp_data_max = self.frame_parent.my_loaded_volumes[0][0].data_max
            self.frame_parent.tmp_data_min = self.frame_parent.my_loaded_volumes[0][0].data_min
            self.DataMax.SetLabel('Data maximum: %s' %str(self.frame_parent.tmp_data_max))
            self.DataMin.SetLabel('Data minimum: %s' %str(self.frame_parent.tmp_data_min))                
            
        elif choice != '':
            for i in range(len(self.frame_parent.my_loaded_volumes)):
                try:
                    if self.frame_parent.my_loaded_volumes[i][0].data_label == choice:
                        max = self.frame_parent.my_loaded_volumes[i][0].data_max
                        min = self.frame_parent.my_loaded_volumes[i][0].data_min
                        self.DataMax.SetLabel('Data maximum: %s' %str(max))
                        self.DataMin.SetLabel('Data minimum: %s' %str(min))
                        self.index_to_data = i
                except:
                    self.DataMax.SetLabel('Data maximum: not selected')
                    self.DataMin.SetLabel('Data minimum: not selected')
        else:
            self.DataMax.SetLabel('Data maximum: not selected')
            self.DataMin.SetLabel('Data minimum: not selected')






class DialogSurfaceGenerate(wx.Panel):
    #allows the user to select one of the loaded volumes to interrogate

    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)
        
        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent
        self.index_to_data = 0
        
        drop_down_content = [] #the list holder for the volume selection
        drop_down_content.append('')
        drop_down_content.append('Base volume')
        
        #scan all loaded volumes not base, tal, or ref (start at 4th element)
        
        for i in range(3,len(self.frame_parent.my_loaded_volumes)):
            #check if any objects are associated with them therefore if list items exist
            for j in range(len(self.frame_parent.ListOfObjects)):
                #as before ..
                try:
                    if self.frame_parent.ListOfObjects[j].my_loaded_volumesindex == i:
                        label = self.frame_parent.ListOfObjects[j].my_label
                        if drop_down_content[-1] == label:
                            pass
                        else:
                            drop_down_content.append(label)
                except:
                    pass

        self.VolumeChoiceLabel = wx.StaticText(id=-1, label='Choose a loaded volume:', name='ChooseVol',
              parent=self, pos=wx.Point(16, 16), style=0)
        
        self.VolumeChoice = wx.Choice(choices=drop_down_content, id=-1,
              name='VolumeChoice', parent=self, pos=wx.Point(16, 42),
              size=wx.Size(250, 21), style=0)
        self.VolumeChoice.Bind(wx.EVT_CHOICE, self.OnVolumeChoice,
              id=-1)
        
        self.DataMax = wx.StaticText(id=-1, label='Data maximum: not selected', name='DataMax',
              parent=self, pos=wx.Point(16, 80), style=0)
        
        self.DataMin = wx.StaticText(id=-1, label='Data minimum: not selected', name='DataMin',
              parent=self, pos=wx.Point(16, 100), style=0)

        self.ExtractionThresholdLabel = wx.StaticText(id=-1, label='Set the extraction threshold:', name='extThrLab',
              parent=self, pos=wx.Point(16, 135), style=0)

        self.ExtractionThreshold = wx.TextCtrl(id=-1, name='ExtractThr',
              parent=self, pos=wx.Point(175, 130), size=wx.Size(75, 20),
              style=wx.TE_RIGHT, value='0')
        self.ExtractionThreshold.SetEditable(1)


        self.SmoothingLabel = wx.StaticText(id=-1, label='Amount of smoothing \n(min = 1 max = 10):', name='extThrLab',
              parent=self, pos=wx.Point(16, 165), style=0)

        self.Smoothing = wx.TextCtrl(id=-1, name='Smoothing',
              parent=self, pos=wx.Point(175, 170), size=wx.Size(75, 20),
              style=wx.TE_RIGHT, value='1')
        self.Smoothing.SetEditable(1)

        self.ConnLabel = wx.StaticText(id=-1, label='Extract: ', name='extConns',
              parent=self, pos=wx.Point(16, 245), style=0)
        self.ConnectionChoice = wx.Choice(self, -1, (100, 245), choices = ('All surfaces','Largest connected'))

        self.GenerateSurface = wx.Button(self, -1, 'Run', (225,275))
        self.Bind(wx.EVT_BUTTON, self.OnGenerateSurfaceButton, self.GenerateSurface)

        self.SpreadChkBx = wx.CheckBox(id=-1,
              label='Generate as distribution', name='spreadGen',
              parent=self, pos=wx.Point(16, 210), 
              style=0)
        self.SpreadChkBx.SetValue(False)
    
    def mu(self):
        for i in range(10):
            time.sleep(1)
    
    def OnGenerateSurfaceButton(self, evt):
        ind = self.index_to_data
        data_vol = self.frame_parent.my_loaded_volumes[ind][0].volume_data
        data_source_path = self.frame_parent.my_loaded_volumes[ind][0].data_source_path
        thr = self.ExtractionThreshold.GetValue()
        thr = thr.split(',')
        reduction_factor = int(self.Smoothing.GetValue())
        print reduction_factor
        if reduction_factor < 1:
            reduction_factor = 1
        elif reduction_factor > 10:
            reduction_factor = 10
    
        if self.SpreadChkBx.GetValue() == True:
            # if the usr wants to view the distribution of the activation
            #  we create a table of colour and transparencies to assign
            #  to aid this
            #  also we create a group for all surfaces in the tree control
            new_surface_group = self.frame_parent.tree.AppendItem(self.frame_parent.tree_overlays, '3D overlay group')
            
            if len(thr) > 1:
                my_colours = []
                for i in range(len(thr)):
                    my_tint = float((i+1)*(1/float(len(thr))))
                    my_colours.append((1.0, my_tint, 0,))
                    self.parent.Destroy()
                    connectivity = self.ConnectionChoice.GetSelection()
                    Generate_surface_from_loaded_volume(thr[i], data_vol, self.frame_parent, self.frame_parent.tmp_data_max, data_source_path, reduction_factor, my_colours[i], my_tint, new_surface_group, 1, connectivity)            
        
        else:
            self.parent.Destroy()
            #threading.Thread(self.mu())            
            for i in range(len(thr)):
                connectivity = self.ConnectionChoice.GetSelection()
                #loop through multiple surfaces if provided
                Generate_surface_from_loaded_volume(thr[0], data_vol, self.frame_parent, self.frame_parent.tmp_data_max, data_source_path, reduction_factor, (0.5,0.5,0.5), 1, self.frame_parent.tree_overlays, 0, connectivity)
        
        
    def OnVolumeChoice(self, evt):
        choice = self.VolumeChoice.GetStringSelection()

        if choice == 'Base volume':
            self.frame_parent.tmp_data_max = self.frame_parent.my_loaded_volumes[0][0].data_max
            self.frame_parent.tmp_data_min = self.frame_parent.my_loaded_volumes[0][0].data_min
            self.DataMax.SetLabel('Data maximum: %s' %str(self.frame_parent.tmp_data_max))
            self.DataMin.SetLabel('Data minimum: %s' %str(self.frame_parent.tmp_data_min))                
            
        elif choice != '':
            for i in range(len(self.frame_parent.my_loaded_volumes)):
                try:
                    if self.frame_parent.my_loaded_volumes[i][0].data_label == choice:
                        max = self.frame_parent.my_loaded_volumes[i][0].data_max
                        min = self.frame_parent.my_loaded_volumes[i][0].data_min
                        self.DataMax.SetLabel('Data maximum: %s' %str(max))
                        self.DataMin.SetLabel('Data minimum: %s' %str(min))
                        self.index_to_data = i
                except:
                    self.DataMax.SetLabel('Data maximum: not selected')
                    self.DataMin.SetLabel('Data minimum: not selected')
        else:
            self.DataMax.SetLabel('Data maximum: not selected')
            self.DataMin.SetLabel('Data minimum: not selected')

            


class DialogSurfaceSelection(wx.Panel):
    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)

        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent

        self.radioBox1 = wx.RadioBox(choices=['SurfRelax file (.off)',
                                              'VTK polydata (.vtk)',
                                              'mrVista surface files (.MRM, .mrp, .class)',
                                              'FreeSurfer surface'],
              id=-1,label='Select the type of surface you want to load:', majorDimension=1, name='radioBox1',
              parent=self, pos=wx.Point(20, 20), size=wx.Size(250, 90),
              style=wx.RA_SPECIFY_COLS)
        
        self.SelectionConfirm = wx.Button(id=-1, label='Load',
              name='BrowseBtn', parent=self, pos=wx.Point(220, 150),
              size=wx.Size(50, 23), style=0)
        self.SelectionConfirm.Bind(wx.EVT_BUTTON, self.OnSelectionConfirmButton,
              id=-1)
        
    def OnSelectionConfirmButton(self, event):
        my_type = self.radioBox1.GetStringSelection()
        #self.frame_parent.a,self.frame_parent.b = Load_OFF_File(self, self.frame_parent)
        if my_type == 'SurfRelax file (.off)':
            self.parent.Destroy()
            Load_OFF_File(self, self.frame_parent)
            

        if my_type == 'FreeSurfer surface':
            self.parent.Destroy()
            Load_FS_File(self, self.frame_parent)
            

        if my_type == 'VTK polydata (.vtk)':
            self.parent.Destroy() 
            LoadVTKPolyDataFile(self, self.frame_parent)





class DialogSurfaceExport(wx.Panel):
    def __init__(self, parent, frame_parent):
        wx.Panel.__init__(self, parent, -1)  
        
        #some constants to allow handling later
        self.parent = parent
        self.frame_parent = frame_parent
        self.index_to_data = 0
        
        drop_down_content = [] #the list holder for the volume selection
        drop_down_content.append('')
        
        #scan all objects to find those suitabel for export        
        for j in range(len(self.frame_parent.ListOfObjects)):
            #try:
                if self.frame_parent.ListOfObjects[j].my_type in ['MinNormType1', \
                                                                  'vtkPolyDataSurfaceFromOFF', \
                                                                  'vtkPolyDataProbeOutputSurface', \
                                                                  'vtkPolyDataSurfaceFromLoadedVolume']:
                    label = self.frame_parent.ListOfObjects[j].my_label
                    if drop_down_content[-1] == label:
                        pass
                    else:
                        drop_down_content.append(label)
            #except:
            #    pass
        
        if drop_down_content == ['']:
            print 'No surfaces suitable for export loaded / generated yet.'
            self.parent.Destroy()
        
        self.SurfaceChoiceLabel = wx.StaticText(id=-1, label='Choose a surface to export:', name='ChooseSurface',
              parent=self, pos=wx.Point(16, 16), style=0)
        
        self.SurfaceChoice = wx.Choice(choices=drop_down_content, id=-1,
              name='SurfaceChoice', parent=self, pos=wx.Point(16, 42),
              size=wx.Size(250, 21), style=0)
        
        self.DoExport = wx.Button(self, -1, 'Export Now', (100,200))
        self.Bind(wx.EVT_BUTTON, self.OnDoExportButton, self.DoExport)


    def OnDoExportButton(self, event):
        choice = self.SurfaceChoice.GetStringSelection()
        for j in range(len(self.frame_parent.ListOfObjects)):
            try:
                if choice == self.frame_parent.ListOfObjects[j].my_label:
                    
                    dlg = wx.FileDialog(self.frame_parent, "Save your surface file here:", "", "", ".vtk file|*.vtk", wx.SAVE)
        
                    if dlg.ShowModal() == wx.ID_OK:
                        file_to_save = dlg.GetPath()
                    else:
                        return
                    
                    dv3dExportPolyDataToDotVTKFile(file_to_save, self.frame_parent.ListOfObjects[j])
            except:
                print 'export failed for some reason (?) ...'
                pass #TODO fix
                
        







class MyDialogFrame(wx.Frame):
    def __init__(self, frame_parent, type):
        wx.Frame.__init__(self, None, -1, 'Input required ...',  size=(330, 330), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE)
        #check which type of object we are creating a property panel for
        # and call the appropriate panel class
                
        #if we are dealing with the 'base' image ...
        if type == 'DialogSurfaceSelection':
            panel = DialogSurfaceSelection(self, frame_parent)

        elif type == 'DialogSurfaceGenerate':
            panel = DialogSurfaceGenerate(self, frame_parent)
            
        elif type == 'DialogSurfaceExport':
            panel = DialogSurfaceExport(self, frame_parent)

        elif type == 'DialogMNIGlassBrainSurface':
            LoadVTKPolyDataFile(self, frame_parent, MNIGlassBrain=1)
            gb = frame_parent.ListOfObjects[-1]
            propertyBack = vtk.vtkProperty()
            propertyBack.SetDiffuseColor(1.0, 0.5, 0.4)
            propertyBack.SetOpacity(0.05)
            gb.GetProperty().SetColor(1.0,1.0,1.0)
            gb.GetProperty().SetOpacity(0.05)
            gb.SetBackfaceProperty(propertyBack)
            frame_parent.ren.Render()
            frame_parent.widget.Render()
            
            gb.GetProperty().SetRepresentationToWireframe()
            frame_parent.ren.Render()
            frame_parent.widget.Render()
            
            
          
        elif type == 'ColourChooser':
            panel = ColourSelection(self, frame_parent)
            
        elif type == 'ContourPlot3D':
            panel = ContourPlot3D_Selection(self, frame_parent)
            
        elif type == 'MinNorm_Type1':
            panel = MinimumNorm_Type1_Selection(self, frame_parent)
            
        elif type == 'Dipole_4DNI':
            panel = Dipole_4DNI_Selection(self, frame_parent)      
            
        #self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        
        
    #def OnCloseWindow(self, event):
        #self.Show(False)
