import vtk
import os, sys
from struct import calcsize, unpack
from numpy import *
from dv3dObjectsToRender import *
from dv3dPropertyFrames import *
import wx

def LoadVTKPolyDataFile(self, frame_parent, MNIGlassBrain=0):
    
    if MNIGlassBrain != 0:
        try:
            vertex_file = './DV3D_essentials/mni_surface_5500_3mm.vtk'
        except:
            if frame_parent.AutoLoadFileNow == '':
                dlg = wx.FileDialog(self, "Choose vtk polydata file:", '', "", "*.vtk", wx.OPEN)
                if dlg.ShowModal() == wx.ID_OK:
                    self.data_source_path = dlg.GetPath()
                else:
                    return
            
                vertex_file = self.data_source_path
                
                if vertex_file == None:
                    return
 
            else:
                vertex_file = frame_parent.AutoLoadFileNow
   
    elif frame_parent.AutoLoadFileNow == '':
        dlg = wx.FileDialog(self, "Choose vtk polydata file:", '', "", "*.vtk", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.data_source_path = dlg.GetPath()
        else:
            return
    
        vertex_file = self.data_source_path
        
        if vertex_file == None:
            return
    
    else:
        vertex_file = frame_parent.AutoLoadFileNow
    
    surface, mn_Mapper = CreateVTKPolyDataSurface(frame_parent, vertex_file)
    
    surface.vertex_file = vertex_file
    
    #AddVTKObjectWithAttributes(surface,\
    #                    frame_parent,\
    #                    'MinNormType1',\
    #                    'Min Norm Surface',\
    #                    None,\
    #                    None,\
    #                    0,\
    #                    1,\
    #                    1,\
    #                    'structural',\
    #                    None,\
    #                    'None',\
    #                    1,\
    #                    'MinNormType1',\
    #                    None)


    #cone = vtk.vtkConeSource()
    #cone.SetResolution(8)
    #
    #cone.SetRadius(50)
    #cone.SetHeight(100)
    #cone.SetCenter(100,100,100)
    #
    #coneMapper = vtk.vtkPolyDataMapper()
    #coneMapper.ImmediateModeRenderingOn()
    #coneMapper.SetInput(cone.GetOutput())
    #
    #coneActor = vtk.vtkActor()
    #coneActor.SetMapper(coneMapper)
    #
    ##coneActor.GetProperty().BackfaceCullingOn()
    #coneActor.GetProperty().SetOpacity(0.5)
    #coneActor.GetProperty().SetEdgeVisibility(0)
    

    AddVTKObjectWithAttributes(surface,\
                            frame_parent,\
                            'vtkPolyDataSurfaceFromOFF',\
                            'surface',\
                            None,\
                            None,\
                            0,\
                            1,\
                            1,\
                            'functional',\
                            None,\
                            'None',\
                            1,\
                            'SurfaceProperties',\
                            None)

    #AddVTKObjectWithAttributes(surface,\
    #                        frame_parent,\
    #                        'vtkPolyDataSurfaceFromOFF',\
    #                        'surface',\
    #                        None,\
    #                        None,\
    #                        0,\
    #                        1,\
    #                        1,\
    #                        'structural',\
    #                        None,\
    #                        'None',\
    #                        1,\
    #                        'SurfaceProperties',\
    #                        None)
    
    ###TODO URGENT FIX
    ###frame_parent.ortho_window.ortho_ren1.AddActor(frame_parent.ListOfObjects[-1])
    ###frame_parent.ortho_window.ortho_ren2.AddActor(frame_parent.ListOfObjects[-1])
    ###frame_parent.ortho_window.ortho_ren3.AddActor(frame_parent.ListOfObjects[-1])
    frame_parent.ren.AddActor(frame_parent.ListOfObjects[-1])
    
    #frame_parent.ortho_ren1.AddActor(frame_parent.ListOfObjects[-1])
    #frame_parent.ortho_ren2.AddActor(frame_parent.ListOfObjects[-1])
    #frame_parent.ortho_ren3.AddActor(frame_parent.ListOfObjects[-1])    
   
    
    #apply the new table for later referecnce - tag it to the volume                        
    #frame_parent.ListOfObjects[-1].lookuptable = lookuptable
    #frame_parent.ListOfObjects[-1].GetMapper().SetLookupTable(lookuptable)
    #frame_parent.ListOfObjects[-1].time_series_data = time_series_data
    #frame_parent.ListOfObjects[-1].ScalarValues = mn_ScalarValues
    #frame_parent.ListOfObjects[-1].PolyData = mn_PolyData
    #frame_parent.ListOfObjects[-1].Mapper = mn_Mapper
    
    if MNIGlassBrain != 0:
        frame_parent.ListOfObjects[-1].my_label = 'MNI glass brain'
    
    new_surface = frame_parent.tree.AppendItem(frame_parent.tree_structural, frame_parent.ListOfObjects[-1].my_label)
    #add the newly created treeitem as an atribute of the plane_group
    frame_parent.ListOfObjects[-1].my_treeitem = new_surface


    frame_parent.tree.Refresh()
    
    # .. create a properties window for the plane set ...
    # we pass the parent frame and the newly created object as args
    frame = MyPropertyFrame(frame_parent, frame_parent.ListOfObjects[-1], 0)
    frame.Show(True)
    
    # ... and apply it to the relevant list object
    frame_parent.ListOfObjects[-1].my_property_frame_instance = frame
    
    align_all_planes(frame_parent)





def CreateVTKPolyDataSurface(frame_parent, vertex_file):
    try_me = vtk.vtkPolyDataReader()
    try_me.SetFileName(vertex_file)    
    
    #correct freesurfer offset if required
    xfm = vtk.vtkTransform()
    #if frame_parent.applyVTKxfm == 1:
    if vertex_file[-6:-5] != 'o':    
        xfm.Translate(0, 0, 0)
        #xfm.Translate(88, 128, 128)
        #xfm.Scale(-1.0, 1.0, 1.0)
    else:
        xfm.Translate(0, 0, 0)
        xfm.Scale(1.0, 1.0, 1.0)
        frame_parent.applyVTKxfm = 1
    
    transformer1 = vtk.vtkTransformPolyDataFilter()
    transformer1.SetInput(try_me.GetOutput())
    transformer1.SetTransform(xfm)

    #mn_PolyData = try_me.GetOutput()
    mn_PolyData = transformer1.GetOutput()
    mn_PolyData.Update()
    
    
    #d = vtk.vtkDecimatePro()
    #d.SetInput(mn_PolyData)
    #d.SetTargetReduction(0.5)
    #d.PreserveTopologyOff()
    #d.PreserveTopologyOff()
    #d.SplittingOff()
    #d.Update()
    
    
    t = vtk.vtkSmoothPolyDataFilter()
    #t = vtk.vtkWindowedSincPolyDataFilter()
    t.SetNumberOfIterations(0)
    t.SetInput(mn_PolyData)
    #t.SetInput(d.GetOutput())
    t.Update()
    
    mn_PolyData = t.GetOutput()
    
    #mn_curr_pos = 0
    
    #for i in range(7536):
    #    initial_scalars.InsertNextValue(mn_data[i][mn_curr_pos])
    
    #mn_ScalarValues.SetScalars(initial_scalars)
    
    mn_PolyData.Update()
    
    mn_Mapper = vtk.vtkPolyDataMapper()
    mn_Mapper.ImmediateModeRenderingOn()
    mn_Mapper.SetInput(mn_PolyData)
    mn_Mapper.ScalarVisibilityOff()
    
    mn_Mapper.Update()
    
    my_mnorm_brain = vtk.vtkLODActor()

    my_mnorm_brain.SetMapper(mn_Mapper)
        
    ###allows us to scaling about the object's center later if we want
    ##my_mnorm_brain.SetOrigin(my_mnorm_brain.GetCenter())
        
    my_mnorm_brain.GetProperty().SetColor(0.2,0.2,0.2)
    #my_mnorm_brain.SetBackfaceProperty(property2)
    #my_mnorm_brain.SetScale(1.01, 1.01, 1.01)
    
    #max_in_data = 300 #max(max(reshape(mn_data,(1,sz0*sz1))))
    #build a new lookuptable with the new range - but existing colours in the HSVA ramp
    
    #y = vtk.vtkLookupTable()
    #y.SetNumberOfTableValues(256)
    #y.SetHueRange(0.0, 0.1667)
    #y.SetValueRange(1.0, 1.0)
    #y.SetSaturationRange(1.0, 1.0)
    #y.SetAlphaRange(1.0, 1.0)
    #y.SetTableRange(5.0, max_in_data*1.05)
    #y.Build()
    #y.SetTableValue(0, (0.0,0.0,0.0,0.0))
    
    
    #my_mnorm_brain.GetMapper().SetLookupTable(y)

    return my_mnorm_brain, mn_Mapper
