import vtk
import wx
from numpy import *
from stc_io import *
from dv3dFreeSurferLoad import *
import time
from dv3dObjectsToRender import *
import dv3dPropertyFrames
from dv3dFreeSurferLoad import *
from common_functions import align_all_planes

import dv3dSTC_ProbeShepardVolumeData


def loadSTC(the_parent_frame, sample_to_load):
	
	frame_parent = the_parent_frame
	
	stc_filename = ''
	dlg = wx.FileDialog(the_parent_frame, "Choose the STC file:", "", "", "*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            stc_filename = dlg.GetPath()
	
	if stc_filename == '':
		stc_filename = './stc_examples/StimOnset_Active_Low_white-lh.stc'
		print 'chose default stc file: '+stc_filename
	
	
	surf_filename = ''
	dlg2 = wx.FileDialog(the_parent_frame, "Choose the surface file:", "", "", "*", wx.OPEN)
        if dlg2.ShowModal() == wx.ID_OK:
            surf_filename = dlg2.GetPath()
	
	if surf_filename == '':
		surf_filename = './stc_examples/lh.white'
		print 'chose default surface file: '+surf_filename
	
	#stc_filename = './stc_examples/ind-lh.stc'
	#surf_filename = './stc_examples/ind.ynic'
	v,timeseries_data,start_ms,sample_ms = read_stc(stc_filename)
	vertices, triangles = read_fs_surf(surf_filename)
	
	scalar_verts = vertices[v]
	
	sc_points = vtk.vtkPoints()
	for i in range(len(scalar_verts)):
		sc_points.InsertPoint(i,scalar_verts[i,0],scalar_verts[i,1],scalar_verts[i,2])
	
	#timeseries_data.max() = timeseries_datatimeseries_data.max()/timeseries_data.max()

	mmax = timeseries_data.max()
	mmin = timeseries_data.min()
	
		#get the required scalar range from the user
	rsr_min = float(wx.GetTextFromUser(message='Min=%.2e; Max=%.2e; \n\nAt what porpotion of the range (0.0 -1.0) would you like to clip the minumum value \n(i.e. to show all values below 20 percent of the maximum as grey type 0.2)?' %(mmin,mmax), caption='Scalar proportion minimum (0.0 - 1.0)...', default_value='0.2', parent=frame_parent))
	rsr_max = float(wx.GetTextFromUser(message='Min=%.2e; Max=%.2e; \n\nAt what porpotion of the range (0.0 -1.0) would you like to clip the maximum value \n(i.e. to show all values above 50 percent of the maximum as the same colour type 0.5)?', caption='scalar proportion Maximum (0.0 - 1.0)...', default_value='0.5', parent=frame_parent))
	
	#find index of max in array
	x=timeseries_data.argmax()
	dims = timeseries_data.shape
	id_max = unravel_index(x, dims)
	print id_max

	#gen fs surface
	polyData = get_surf_polyData (vertices, triangles)
	
	origMapper = vtk.vtkPolyDataMapper()
	origMapper.ImmediateModeRenderingOn()
	origMapper.SetInput(polyData)
	origMapper.Update()
	origSurface = vtk.vtkLODActor()
	origSurface.SetMapper(origMapper)
	
	Actor_to_add, colourBar = prepareShepardVolume(frame_parent, sample_to_load, sc_points, timeseries_data, origSurface, rsr_min, rsr_max)
	
	AddVTKObjectWithAttributes(Actor_to_add,\
							the_parent_frame,\
							'vtkSTCSurface',\
							'STCsurface',\
							None,\
							None,\
							0,\
							1,\
							1,\
							'structural',\
							None,\
							stc_filename,\
							1,\
							'STC_Properties',\
							None)

	the_parent_frame.ren.AddActor(the_parent_frame.ListOfObjects[-1])
	
	the_parent_frame.ListOfObjects[-1].timeseries_data = timeseries_data
	the_parent_frame.ListOfObjects[-1].curr_timepoint = 0
	the_parent_frame.ListOfObjects[-1].surface_data = origSurface
	the_parent_frame.ListOfObjects[-1].sc_points = sc_points
	the_parent_frame.ListOfObjects[-1].start_ms = start_ms
	the_parent_frame.ListOfObjects[-1].sample_ms = sample_ms
	the_parent_frame.ListOfObjects[-1].surface_source_path = surf_filename
	colourBar.SetInteractor(the_parent_frame.widget)
	the_parent_frame.ListOfObjects[-1].myScalarBar = colourBar
	the_parent_frame.ListOfObjects[-1].rsr_min = rsr_min
	the_parent_frame.ListOfObjects[-1].rsr_max = rsr_max
	
	colourBar.On()
	
	new_surface = the_parent_frame.tree.AppendItem(the_parent_frame.tree_structural, the_parent_frame.ListOfObjects[-1].my_label)
	#add the newly created treeitem as an atribute of the plane_group
	the_parent_frame.ListOfObjects[-1].my_treeitem = new_surface
	the_parent_frame.tree.Refresh()
	
	# .. create a properties window for the plane set ...
	# we pass the parent frame and the newly created object as args
	frame = dv3dPropertyFrames.MyPropertyFrame(the_parent_frame, the_parent_frame.ListOfObjects[-1], 0)
	frame.Show(True)
	
	# ... and apply it to the relevant list object
	the_parent_frame.ListOfObjects[-1].my_property_frame_instance = frame
	
	the_parent_frame.widget.Render()
	the_parent_frame.ren.ResetCamera()
	the_parent_frame.widget.Render()


def prepareShepardVolume(frame_parent, sample_to_load, sc_points, timeseries_data, full_surface, rsr_min, rsr_max):
	
	mmax = timeseries_data.max()
	mmin = timeseries_data.min()
	
	sc_scalars = vtk.vtkFloatArray()
	for i in range(len(timeseries_data[:,sample_to_load])):
		val = timeseries_data[i,sample_to_load]/mmax
		sc_scalars.InsertNextValue(val)
		#print val
			
	scVertices = vtk.vtkPolyData()
	scVertices.SetPoints(sc_points)
	scVertices.GetPointData().SetScalars(sc_scalars)
	scVertices.Update()
	
	bounds = array(scVertices.GetBounds())
	bounds[0:6:2] =  bounds[0:6:2]-20
	bounds[1:7:2] =  bounds[1:7:2]+20
	
	shepard = vtk.vtkShepardMethod()
	shepard.SetInput(scVertices)
	shepard.SetModelBounds(bounds)
	shepard.SetMaximumDistance(0.1)
	shepard.SetNullValue(1)
	shepard.SetSampleDimensions(50, 50, 50)
	shepard.Update()
	
	updatedActor, colourBar = dv3dSTC_ProbeShepardVolumeData.ProbeShepardVolume(frame_parent, full_surface, shepard.GetOutput(), mmin, mmax, rsr_min, rsr_max)
	return updatedActor, colourBar
