from win32com.client import constants as c
import os
xsi = Application


# Some Vars
maketx_batch = (os.environ['TEMP'] if os.environ.has_key('TEMP') else os.environ['TMP']) + "\\maketx_batch.bat"


#	Do not adjust
filters = ["box (default)", "box", "triangle", "triangle", "gaussian", "gaussian", "catrom", "catrom", "blackman-harris", "blackman-harris", "sinc", "sinc", "lanczos3", "lanczos3", "radial-lanczos3", "radial-lanczos3", "mitchell", "mitchell", "bspline", "bspline", "disk", "disk"]
imageExts = ("tif", "tiff", "png", "jpg", "jpeg", "exr")


###################################################################
###################################################################
###################								###################
###################			Plugin				###################
###################								###################
###################################################################
###################################################################
#
#
#
#
#
def XSILoadPlugin( in_reg ):
	in_reg.Author = "Vincent Ullmann"
	in_reg.Name = "vu_txManager_Plugin"
	in_reg.Major = 0
	in_reg.Minor = 6
	in_reg.Categories = "render"

	in_reg.RegisterCommand("vu_txManager_Cmd","vu_txManager_Cmd")
	in_reg.RegisterMenu(c.siMenuMainFileSceneID,"vu_txManager_Menu",False,False)
	in_reg.RegisterProperty("vu_txManager_PPG")
	#RegistrationInsertionPoint - do not remove this line
	return True


def XSIUnloadPlugin( in_reg ):
	strPluginName = in_reg.Name
	Application.LogMessage(str(strPluginName) + str(" has been unloaded."),c.siVerbose)
	return True


# Menu
def vu_txManager_Menu_Init( in_ctxt ):
	in_ctxt.Source.AddCommandItem("txManager","vu_txManager_Cmd")

# Command
def vu_txManager_Cmd_Execute():
	PPG = xsi.ActiveSceneRoot.AddProperty( "vu_txManager_PPG", False, "txManager")
	xsi.InspectObj( PPG, None, "txManager", c.siLock, False );

###################################################################
###################################################################
###################								###################
###################			Property			###################
###################								###################
###################################################################
###################################################################
#
#
#
#
#
# Create Prop
def vu_txManager_PPG_Define( in_ctxt ):
	PPG = in_ctxt.Source

	# PPG Params
	PPG.AddParameter3("texFolder", c.siString, "" )				#####		FIX THIS !!!!!!!
	PPG.AddParameter3("texFolderSubFolders", c.siBool, False, None, None, False)
	PPG.AddParameter3("source", c.siString, "scene" )
	PPG.AddParameter3("cmdLine", c.siString, "-v")
	PPG.AddParameter3("preset", c.siString, "--oiio")
	PPG.AddParameter3("filter", c.siString, "lanczos3")

	# GridData
	gridPar = PPG.AddGridParameter("grid").Value
	gridPar.ColumnCount = 2
	gridPar.SetColumnType( 0, c.siColumnBool )
	gridPar.SetColumnLabel( 0, "MakeTX" )
	gridPar.SetColumnType( 1, c.siColumnStandard )	# FileName
	gridPar.SetColumnLabel( 1, "FileName" )

# Create Layout
def vu_txManager_PPG_DefineLayout( in_ctxt ):
	oLayout = in_ctxt.Source
	oLayout.Clear()

	oLayout.AddRow()
	oLayout.AddGroup("", False) # Left Side


	oLayout.AddGroup("Found Textures")
	gridLay = oLayout.AddItem("grid")
	gridLay.SetAttribute( "NoLabel", True )
	gridLay.SetAttribute( "HideRowHeader", True )
	oLayout.EndGroup()


	oLayout.EndGroup() #Left Side
	oLayout.AddGroup("", False) # Right Side


	oLayout.AddGroup("Source")
	oLayout.AddRow()
	ppgItem = oLayout.AddEnumControl( "source", ["Use Scene Textures", "scene", "Use Folder Textures", "folder"], "Source:", c.siControlRadio );
	ppgItem.SetAttribute( "NoLabel", True )
	oLayout.AddButton("refresh",			"Refresh")
	oLayout.EndRow()
	oLayout.AddGroup("Textures Folder")
	ppgItem = oLayout.AddItem("texFolder", "", c.siControlFolder)
	ppgItem.SetAttribute( "NoLabel", True )
	ppgItem = oLayout.AddItem("texFolderSubFolders", "Search in SubFolders")
	oLayout.EndGroup() # TexFolder
	oLayout.EndGroup() # Source

	oLayout.AddGroup("Select") #Buttons
	oLayout.AddRow()
	oLayout.AddButton("selAll",			"Select All")
	oLayout.AddButton("selNone",		"Select None")
	oLayout.AddButton("selUnpro",		"Select Unprocessed")
	oLayout.AddButton("selPro",			"Select Processed")
	oLayout.AddButton("selInv",			"Invert Selection")
	oLayout.EndRow()
	oLayout.EndGroup()

	oLayout.AddGroup("Options")

	oLayout.AddRow()
	oLayout.AddGroup("Custom:")
	ppgItem = oLayout.AddItem("cmdLine", "")
	ppgItem.SetAttribute( "NoLabel", True )
	oLayout.EndGroup()

	oLayout.AddGroup("Preset:")
	ppgItem = oLayout.AddEnumControl( "preset", ["- None -", "", "--oiio", "--oiio", "--prman", "--prman"], "", c.siControlCombo)
	ppgItem.SetAttribute( "NoLabel", True )
	oLayout.EndGroup()

	oLayout.AddGroup("Filter:")
	ppgItem = oLayout.AddEnumControl( "filter", filters, "", c.siControlCombo)
	ppgItem.SetAttribute( "NoLabel", True )
	oLayout.EndGroup()
	oLayout.EndRow()
	oLayout.EndGroup() # CommandLine


	oLayout.AddGroup("Buttons", False)
	oLayout.AddRow()
	oLayout.AddGroup("Create")
	oLayout.AddButton("createTx",	"create .tx Textures")
	oLayout.EndGroup()
	oLayout.AddGroup("Delete")
	oLayout.AddButton("deleteTx",	"delete .tx Textures")
	oLayout.EndGroup()
	oLayout.EndRow()
	oLayout.EndGroup()




	oLayout.AddGroup("Info")
	oLayout.AddRow()
	oLayout.AddStaticText("Green\nYellow\nRed")
	oLayout.AddStaticText("=\n=\n=")
	oLayout.AddStaticText("Texture has a TX-File\nTexture has no TX-File\nTX-File is older than the Original")
	oLayout.EndRow()
	oLayout.AddStaticText("\ntxManager by Vincent Ullmann")
	oLayout.AddStaticText("\ninspired by the original txManager from MtoA")
	oLayout.EndGroup()

	oLayout.EndGroup() # Right Side











###################################################################
###################################################################
###################								###################
###################			Helpers				###################
###################								###################
###################################################################
###################################################################
#
#
#
#
#
def SetCellColor(gridPar,column, row, r,g,b):
	color = gridPar.GetCellBackgroundColor( column, row )
	color.Red = r
	color.Green = g
	color.Blue = b
	gridPar.SetCellBackgroundColor( column, row, color )


def hasTX(filename):
	txname = ".".join(filename.split(".")[:-1]) + ".tx"
	return os.path.isfile(txname)


def txIsOld(filename):
	txname = ".".join(filename.split(".")[:-1]) + ".tx"
	return os.path.getmtime(filename) > os.path.getmtime(txname)


def updateSel(gridPar):
	gridPar = PPG.grid.value
	for i in range(gridPar.RowCount):
		filename = gridPar.GetCell(1, i)
		gridPar.SetCell(0, i, not hasTX(filename) or txIsOld(filename))



def updateData(texfiles):
	gridPar = PPG.grid.value

	# Delete all old Data
	for i in range(gridPar.RowCount):
		gridPar.RemoveRow(0)

	for i, tex in enumerate(texfiles):
		gridPar.InsertRow(i);
		gridPar.SetRowLabel(i, str(i))
		gridPar.SetCellReadOnlyFlags( [1,i], True );

		# Set Filename
		gridPar.SetCell(1, i, tex)

		if not hasTX(tex):		# No txFile
			gridPar.SetCell(0, i, True)
			SetCellColor(gridPar,0, i, 255,200,0)
			SetCellColor(gridPar,1, i, 255,200,0)
		else:
			if txIsOld(tex):	# txFile is older then Texture
				gridPar.SetCell(0, i, True)
				SetCellColor(gridPar,0, i, 255,0,0)
				SetCellColor(gridPar,1, i, 255,0,0)
			else:				# the World is fine
				gridPar.SetCell(0, i, False)
				SetCellColor(gridPar,0, i, 155,155,155)
				SetCellColor(gridPar,1, i, 0,155,0)



def findImagesInFolder():
	if PPG.texFolder.value == "":
		return []

	texfiles = []
	if PPG.texFolderSubFolders.value:
		for root, dirs, files in os.walk(PPG.texFolder.value):
			for filename in files:
				if filename.lower().endswith(imageExts):
					texfiles.append(os.path.join(root, filename))

	else:
		for filename in os.listdir(PPG.texFolder.value):
			if filename.lower().endswith(imageExts):
				texfiles.append(os.path.join(PPG.texFolder.value, filename))

	updateData(texfiles)


def findImagesInScene():
	texfiles = []
	for matlib in xsi.ActiveProject.ActiveScene.MaterialLibraries:
		for mat in matlib.Items:
			for clip in mat.ImageClips:
				filename = clip.Source.Parameters("FileName").Value


				if clip.TimeControl.ClipIn != clip.TimeControl.ClipOut:
					# Fuck! This is a Sequence

					base = filename.split("[")[0]
					ext = filename.split("[")[1].split("]")[1]
					seq = filename.split("[")[1].split("]")[0]
					start = int(seq.split("..")[0])
					end = int(seq.split(";")[0].split("..")[1])
					padd = int(seq.split(";")[1])

					for i in range(start, end+1):
						filename = base + ("000000" + str(i))[-padd:] + ext
						if filename not in texfiles:
							texfiles.append(filename)
				else:
					if filename not in texfiles:
						texfiles.append(filename)

	texfiles.sort()
	updateData(texfiles)


###################################################################
###################################################################
###################								###################
###################			PPG Callbacks		###################
###################								###################
###################################################################
###################################################################
#
#
#
#
#
def vu_txManager_PPG_texFolder_OnChanged():
	findImagesInFolder()
def vu_txManager_PPG_texFolderSubFolders_OnChanged():
	findImagesInFolder()


def vu_txManager_PPG_source_OnChanged():
	if PPG.source.value == "scene":
		PPG.texFolder.ReadOnly = True
		PPG.texFolderSubFolders.ReadOnly = True
		findImagesInScene()
	else:
		PPG.texFolder.ReadOnly = False
		PPG.texFolderSubFolders.ReadOnly = False
		findImagesInFolder()


def vu_txManager_PPG_refresh_OnClicked():
	if PPG.source.value == "scene":
		findImagesInScene()
	else:
		findImagesInFolder()

def vu_txManager_PPG_selAll_OnClicked():
	gridPar = PPG.grid.value
	for i in range(gridPar.RowCount):
		gridPar.SetCell(0, i, True)

def vu_txManager_PPG_selNone_OnClicked():
	gridPar = PPG.grid.value
	for i in range(gridPar.RowCount):
		gridPar.SetCell(0, i, False)

def vu_txManager_PPG_selUnpro_OnClicked():
	gridPar = PPG.grid.value
	updateSel(gridPar)

def vu_txManager_PPG_selPro_OnClicked():
	gridPar = PPG.grid.value
	updateSel(gridPar)
	vu_txManager_PPG_selInv_OnClicked()


def vu_txManager_PPG_selInv_OnClicked():
	gridPar = PPG.grid.value
	for i in range(gridPar.RowCount):
		gridPar.SetCell(0, i, not gridPar.GetCell(0, i))


def vu_txManager_PPG_createTx_OnClicked():
	content = ""
	maketx = "call " + xsi.Plugins("Arnold Render").OriginPath + "\\maketx.exe " + PPG.cmdLine.value + " " + PPG.preset.value  + " --filter " + PPG.filter.value + " "

	gridPar = PPG.grid.value
	for i in range(gridPar.RowCount):
		if gridPar.GetCell(0, i):
			filename = gridPar.GetCell(1, i)
			content += maketx + filename + "\n"
			print "[vu_txManager] Convert: " + filename

	content += "ECHO Y | DEL " + maketx_batch + "\n"
	makeTXbatch = open(maketx_batch, "w")
	makeTXbatch.write(content)
	makeTXbatch.close()
	os.startfile(maketx_batch)


def vu_txManager_PPG_deleteTx_OnClicked():
	gridPar = PPG.grid.value
	for i in range(gridPar.RowCount):
		if gridPar.GetCell(0, i):
			filename = ".".join(gridPar.GetCell(1, i).split(".")[:-1]) + ".tx"
			if os.path.exists(filename):
				print "[vu_txManager] Delete: " + filename
				os.remove(filename)
	vu_txManager_PPG_source_OnChanged()


def vu_txManager_PPG_OnInit():
	findImagesInScene()


def vu_txManager_PPG_OnClosed():
	try:
		xsi.deleteObj("txManager")
	except:
		pass