#########################################################################
#																		#
#							- GJ LIGHT PRESET -							#
#								    V0.4.0								#
#																		#
#							by Guillaume  Jobst							#
#							www.guillaume-j.com							#
#						  contact@guillaume-j.com						#
#																		#
#########################################################################
import maya.mel
import maya.cmds as cmds
import os
import xml.dom.minidom as xml
from xml.dom.minidom import Document
import webbrowser
import urllib

script_version = "0.4.0"

dockSwitch = False
#########################################################################
#   CLASS FOR PREFERENCE FILE CREATION AND READING / WRITING            #
#########################################################################

class PreferenceFile:
	
	def __init__(self):
		#PATH
		self.path = os.environ['MAYA_APP_DIR']
		self.fileName = self.path + os.sep + "LightingPresetPref.txt"

	#Create Preset Fonc	
	def createFile(self):
		
		#DATAS
		self.folder_path_DATA = folder_path[0]
		self.only_Selected_DATA = cmds.checkBox(ui.onlySelected,query=True,value=True)
		self.saveCamera_DATA = cmds.checkBox(ui.saveCamera,query=True,value=True)
		self.saveRenderer_DATA = cmds.checkBox(ui.saveRenderer_checkbox,query=True,value=True)
		self.createLights_DATA = cmds.checkBox(ui.createLights_checkbox,query=True,value=True)
		self.savePersp_DATA = cmds.menuItem(ui.savePersp,query=True,checkBox=True)
		self.grp1Name_DATA = nameGrp1Glo
		self.grp2Name_DATA = nameGrp2Glo
		self.grp3Name_DATA = nameGrp3Glo
		self.deleteXml_DATA = cmds.checkBox(ui.delete_xml_checkbox,query=True,value=True)
		self.warningMode_DATA = cmds.menuItem(ui.displayWarning,query=True,checkBox=True)
		self.debugMode_DATA = cmds.menuItem(ui.debugOpt,query=True,checkBox=True)

		self.datas =['FOLDERPATH=' + str(self.folder_path_DATA)+';',
					 'ONLYSELECTED=' + str(self.only_Selected_DATA)+';',
					 'SAVECAMERA=' + str(self.saveCamera_DATA)+';',
					 'SAVERENDERER=' + str(self.saveRenderer_DATA)+';',
					 'CREATELIGHTS=' + str(self.createLights_DATA)+';',
					 'SAVEPERSP=' + str(self.savePersp_DATA)+';',
					 'GRP1NAME=' + str(self.grp1Name_DATA)+';',
					 'GRP2NAME=' + str(self.grp2Name_DATA)+';',
					 'GRP3NAME=' + str(self.grp3Name_DATA)+';',
					 'DELETEXML=' + str(self.deleteXml_DATA)+';',
					 'WARNINGMODE=' + str(self.warningMode_DATA)+';',
					 'DEBUGMODE=' + str(self.debugMode_DATA)+';']
					 
		fileName = self.fileName
		datas = self.datas
		
		#File
		FILE = open(fileName,"w")
		
		# Alternatively write them one by one:
		for name in datas:
		    FILE.write(str(name)+ '\n')
		    
		FILE.close()
		
		confirm = cmds.confirmDialog( title='Confirm', message='Preferences saved', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
	#Delete Preset Fonc
	def deleteFile(self):
		confirm = cmds.confirmDialog( title='Confirm', message='Delete preference file?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
		if confirm == "Yes":
			try:
				fileName = self.fileName
				os.remove(fileName)
				print "Preference file deleted"
				
			except:
				print "Preference file not found"
		else:
			return
	
	#Reading Fonc
	def readFile(self):
		fileName = self.fileName
		
		FILE = open(fileName, "r")
		
		dataReaded = FILE.read()
		dataReaded = dataReaded.split('\n')
		FILE.close()
		
		#Output Datas
		#Path
		self.folderReaded = dataReaded[0][11:-1]
		#Only Selected
		if dataReaded[1][13:-1] == "True":
			self.onlySelectedReaded = True
		else:
			self.onlySelectedReaded = False
		#Save Camera
		if dataReaded[2][11:-1] == "True":
			self.saveCamera = True
		else:
			self.saveCamera = False
		#Save Renderer
		if dataReaded[3][13:-1] == "True":
			self.saveRenderer = True
		else:
			self.saveRenderer = False
		#Create Lights
		if dataReaded[4][13:-1] == "True":
			self.createLights = True
		else:
			self.createLights = False
		#Save Persp
		if dataReaded[5][10:-1] == "True":
			self.savePersp = True
		else:
			self.savePersp = False
		#GrpNames
		self.grp1Name = dataReaded[6][9:-1]
		self.grp2Name = dataReaded[7][9:-1]
		self.grp3Name = dataReaded[8][9:-1]
		#Delete XML
		if dataReaded[9][10:-1] == "True":
			self.deleteXml = True
		else:
			self.deleteXml = False
		#Warning mode
		if dataReaded[10][12:-1] == "True":
			self.warningMode = True
		else:
			self.warningMode = False
		#Debug mode
		if dataReaded[11][10:-1] == "True":
			self.debugMode = True
		else:
			self.debugMode = False
		
		return [self.folderReaded,
				self.onlySelectedReaded,self.saveCamera,self.saveRenderer,self.createLights,self.savePersp,
				self.grp1Name,self.grp2Name,self.grp3Name,
				self.deleteXml,self.warningMode,self.debugMode]
		
	def openPref(self):
		try:
			fileName = self.fileName
			os.startfile(fileName)
		except:
			cmds.confirmDialog( title='Error', message='Preference file not found.', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			
Preference = PreferenceFile()
#################################################################################################
#   CHECK IF DATAS ARE ALREADY DEFINED OR NOT													#
#################################################################################################

# Check if folderPath exist
try:
   	folder_path
except NameError:
	try:
		if Preference.readFile()[0] == 'one':
			folder_path = ['None']
		else:
			folder_path = [Preference.readFile()[0]]
	except IOError:	
		folder_path = ['None']
#Check if options exist
#Only Selected
try:
	onlySelectedValue
except NameError:
	try:
		onlySelectedValue = Preference.readFile()[1]
	except IOError:	
		onlySelectedValue = False
#Save Camera
try:
	saveCameraValue
except NameError:
	try:
		saveCameraValue = Preference.readFile()[2]
	except IOError:	
		saveCameraValue = False
#Save Renderer
try:
	saveRendererValue
except NameError:
	try:
		saveRendererValue = Preference.readFile()[3]
	except IOError:	
		saveRendererValue = False
#create Lights
try:
	createLightValue
except NameError:
	try:
		createLightValue = Preference.readFile()[4]
	except IOError:	
		createLightValue = False
#Save Persp
try:
	savePerspValue
except NameError:
	try:
		savePerspValue = Preference.readFile()[5]
	except IOError:	
		savePerspValue = False
		
#Delete XML
try:
	deleteXMLvalue
except NameError:
	try:
		deleteXMLvalue = Preference.readFile()[9]
	except IOError:	
		deleteXMLvalue = False
#Warning Mode
try:
	warningModeValue
except NameError:
	try:
		warningModeValue = Preference.readFile()[10]
	except IOError:	
		warningModeValue = False
#Debug Mode
try:
	debugModeValue
except NameError:
	try:
		debugModeValue = Preference.readFile()[11]
	except IOError:	
		debugModeValue = False
		
# Test Name Group exist
global nameGrp1Glo
global nameGrp2Glo
global nameGrp3Glo

try:
	nameGrp1Glo
except NameError:
	try:
		nameGrp1Glo = Preference.readFile()[6]
	except IOError:
		nameGrp1Glo = 'Grp1'
	
try:
	nameGrp2Glo
except NameError:
	try:
		nameGrp2Glo = Preference.readFile()[7]
	except IOError:
		nameGrp2Glo = 'Grp2'
	
try:
	nameGrp3Glo
except NameError:
	try:
		nameGrp3Glo = Preference.readFile()[8]
	except IOError:
		nameGrp3Glo = 'Grp3'
	

# Test if list of preset exist
global list_of_presets
global list_of_presets1
global list_of_presets2
try:
	if list_of_presets is None:
		list_of_presets = []
	else:
		list_of_presets = list_of_presets
except NameError:
	list_of_presets = []
	
try:
	if list_of_presets1 is None:
		list_of_presets1 = []
	else:
		list_of_presets1 = list_of_presets1
except NameError:
	list_of_presets1 = []
	
try:
	if list_of_presets2 is None:
		list_of_presets2 = []
	else:
		list_of_presets2 = list_of_presets2
except NameError:
	list_of_presets2 = []
	
#########################################################################
#    __CLASS__UI___
#########################################################################

class ui():
	
	def __init__(self):
		self.onlySelected = False
		self.saveRenderer_checkbox  = True
		self.createLights_checkbox = False
		self.displayWarning = False
		
	def create(self, dockable):

		if cmds.window("win", exists=True):
			cmds.deleteUI("win", window=True)
			
		if dockable == False:
			if cmds.dockControl("Dock", exists=True):
				cmds.deleteUI("Dock")
		
		# _____MAIN WIN____
		windows = cmds.window( "win", title="Light Presets", docTag = "win", menuBar = True ,
								iconName='Light Presets', maximizeButton = False , widthHeight=(180, 650))
								
		column = cmds.columnLayout( adjustableColumn=True )
		
		#Header
		cmds.iconTextStaticLabel( st='textOnly', l='Lighting Presets v b{0}'.format(script_version) )
		#Folder Path
		cmds.button(annotation ='Setup the folder where all presets will be saved for this session', label='Setup Folder Path' , command = 'ui_input.pick_a_folder()' )
		cmds.button( annotation ='Show the folder currently setuped', label='Show Folder Path' , command = 'ui_input.show_path()' )
		
		# GI PARAM				
		cmds.iconTextStaticLabel( st='textOnly', l='' )
		
		#Only Lights Selected option
		self.onlySelected = cmds.checkBox(annotation ='Save in the preset only selected lights and/or cameras', label='Only Selected', value=onlySelectedValue, cc='onlySelectedValue = cmds.checkBox(ui.onlySelected,query=True,value=True)')
		
		#Save cameras
		self.saveCamera = cmds.checkBox(annotation ='Save also camera parameters (But not top/side/front/persp cameras)', label='Save Camera Param', value=saveCameraValue, cc='saveCameraValue = cmds.checkBox(ui.saveCamera,query=True,value=True);cmds.checkBox(ui.saveOnlyCamera, edit=True, enable = saveCameraValue)')
		self.saveOnlyCamera = cmds.checkBox(annotation ='Save only camera parameters (But not top/side/front/persp cameras)', label='Save Only Camera Param',enable=saveCameraValue, value=False, )#cc='saveCameraValue = cmds.checkBox(ui.saveCamera,query=True,value=True)'
		#Save also renderer
		self.saveRenderer_checkbox = cmds.checkBox(annotation ='Save in the preset also the rendering parameters (Only MentalRay and Vray are supported)', label='Save Renderer Param', value=saveRendererValue, cc='saveRendererValue = cmds.checkBox(ui.saveRenderer_checkbox,query=True,value=True)' )		
		
		#Create Lights options
		self.createLights_checkbox = cmds.checkBox(annotation ='Create light or camera objects from the preset file', label='Create Lights or cameras', value =createLightValue, cc='createLightValue = cmds.checkBox(ui.createLights_checkbox,query=True,value=True)' )
		
		#MENU OF PRESETS
		cmds.iconTextStaticLabel( st='textOnly', l='' )
		
		cmds.button(annotation ='Save a preset', label='Save Preset' , command = 'ui_IO.write(folder_path)' )
		cmds.button(annotation ='Save only renderer parameters', label='Save Only Renderer' , command = 'ui_IO.write_only_renderer()' )
		
		cmds.iconTextStaticLabel( st='textOnly', l='List of presets :' )
		
		form = cmds.formLayout()
		
		#Tabs layout
		self.tabs = cmds.tabLayout(innerMarginWidth=5, innerMarginHeight=5, doubleClickCommand='ui_input.renameTab(reset=False)')
		cmds.formLayout( form, edit=True, attachForm=((self.tabs, 'top', 0), (self.tabs, 'left', 0), (self.tabs, 'bottom', 0), (self.tabs, 'right', 0)) )
		
		#Preset tab
		self.child1 = cmds.columnLayout( 'tab0', adjustableColumn=True)
		
		self.preset_list = cmds.textScrollList(annotation='List of presets (Group: {0} )'.format(nameGrp1Glo), numberOfRows=8, allowMultiSelection=False,
		                        append=list_of_presets,
		                        showIndexedItem=4, 
		                        doubleClickCommand = 'ui_IO.read_from_list()',
		                        deleteKeyCommand = 'ui_IO.delete_preset(list_of_presets, folder_path, all = False)')
		cmds.setParent( '..' )
		
		#Preset tab 1
		self.child2 = cmds.columnLayout('tab1', adjustableColumn=True)		
		self.preset_list1 = cmds.textScrollList(annotation='List of presets (Group: {0})'.format(nameGrp2Glo), numberOfRows=8, allowMultiSelection=False,
		                        append=list_of_presets1,
		                        showIndexedItem=4, 
		                        doubleClickCommand = 'ui_IO.read_from_list()',
		                        deleteKeyCommand = 'ui_IO.delete_preset(list_of_presets, folder_path, all = False)')
		cmds.setParent( '..' )
		
		#Preset tab 2
		self.child3 = cmds.columnLayout('tab2', adjustableColumn=True)		
		self.preset_list2 = cmds.textScrollList(annotation='List of presets (Group: {0})'.format(nameGrp3Glo), numberOfRows=8, allowMultiSelection=False,
		                        append=list_of_presets2,
		                        showIndexedItem=4, 
		                        doubleClickCommand = 'ui_IO.read_from_list()',
		                        deleteKeyCommand = 'ui_IO.delete_preset(list_of_presets, folder_path, all = False)')
		cmds.setParent( '..' )
		
		#Tab edit
		cmds.tabLayout( self.tabs, edit=True, tabLabel=((self.child1, nameGrp1Glo), (self.child2, nameGrp2Glo), (self.child3, nameGrp3Glo)) )
		
		cmds.setParent(column )

		cmds.button(annotation ='Load a preset from the list', label='Load Preset', command ='ui_IO.read_from_list()' )
		
		cmds.button(annotation ='Load a preset from a file', label='Load From File', command ='ui_IO.read_from_file()' )
		
		cmds.button(annotation ='Delete a preset from the list', label='Delete From List' , command ='ui_IO.delete_preset(list_of_presets, folder_path, all = False)' )
		
		#Delete also xml file
		self.delete_xml_checkbox = cmds.checkBox(annotation ='Delete also the .xml file', label='Delete also the .xml file', value=deleteXMLvalue, cc='deleteXMLvalue = cmds.checkBox(ui.delete_xml_checkbox,query=True,value=True)' )
		
		cmds.separator(height=20,visible = not dockable)
		
		cmds.button( annotation = 'Close the UI', visible = not dockable, label='Close', command=('cmds.deleteUI(\"' + windows + '\", window=True)') )
		
		cmds.separator(height=20,visible = not dockable)		

		#Presets Menu
		cmds.menu(label='Presets', tearOff=False )
		cmds.menuItem(annotation = 'Load list from the folder',  label='List From Folder', command = 'ui_input.listFromFolder(folder_path)' )
		cmds.menuItem(annotation = 'Reset Preset List',  label='Reset List', command = 'ui_IO.delete_preset(list_of_presets, folder_path, all = True)' )
		cmds.menuItem(divider=True )
		cmds.menuItem(annotation = 'Open Folder path location',  label='Open Presets Folder', command = "ui_input.open_folder()" )
		cmds.menuItem(annotation = 'Open preset file as text',  label='Open Presets as text', command = "ui_input.open_asText(folder_path)" )
		cmds.menuItem(divider=True )
		self.savePersp = cmds.menuItem(annotation = 'Save also the perspective camera when "Save Camera is ON" ', label='Save Perspective', checkBox=savePerspValue, c='savePerspValue = cmds.menuItem(ui.savePersp,query=True,checkBox=True)')
		#UI menu
		cmds.menu(label='UI', tearOff=False)
		cmds.menuItem(annotation = 'Rename the current group tab',  label='Rename Current Tab', command = 'ui_input.renameTab(reset=False)' )
		cmds.menuItem(annotation = 'Revert tabs group names to default',  label='Reset Tab Names', command = 'ui_input.renameTab(reset=True)' )
		cmds.menuItem(divider=True )
		self.displayWarning = cmds.menuItem(annotation = 'Display a warning when preset is deleted or loaded', label='Display Warning', checkBox=warningModeValue, c='warningModeValue = cmds.menuItem(ui.displayWarning,query=True,checkBox=True)')
		self.debugOpt = cmds.menuItem(annotation = 'Display debug infos in script editor', label='Debug Mode', checkBox=debugModeValue, c='debugModeValue = cmds.menuItem(ui.debugOpt,query=True,checkBox=True)')

		cmds.menuItem(divider=True )
		cmds.menuItem(annotation = 'Allow to dock the window',  label='Dock', command = 'ui.create(dockable=True)' )
		cmds.menuItem(annotation = 'Undock the window', label='unDock', command = 'ui.create(dockable=False)' )
		
		#Preference menu
		cmds.menu(label='Preferences', tearOff=False)
		cmds.menuItem(annotation = 'Save preferences file',  label='Save Preferences', command = 'Preference.createFile()' )
		cmds.menuItem(annotation = 'Delete preferences file',  label='Delete Preferences', command = 'Preference.deleteFile()' )
		cmds.menuItem(annotation = 'Open preferences file as text',  label='Open Preferences', command = 'Preference.openPref()' )
		
		#Help Menu
		cmds.menu( label='Help', tearOff=False )
		cmds.menuItem(annotation = 'Show help', label='Help', command = 'ui_input.show_help()' )
		cmds.menuItem(annotation = 'Show about', label='About', command = 'ui_input.about()' )
		cmds.menuItem(annotation = 'More Info at: www.guillaume-j.com', label='Info', command = "webbrowser.open('http://guillaumejobst.blogspot.co.uk/2012/06/lighting-preset-beta-version.html')" )
		cmds.menuItem(divider=True )
		cmds.menuItem(annotation = 'Check update Online (Can takes few seconds)', label='Check Update Online', command ="ui_input.upDate(script_version,versionOnline=ui_input.findVersion())" )
		
		cmds.formLayout( parent = windows )
		
		if dockable == True:
			dockWin = cmds.dockControl( "Dock", area='left', label = "Lighting Presets", content=windows, allowedArea=["right","left"] )

		cmds.showWindow( windows )
		print ""
		
# UI launcher
dockable = False
ui = ui()
ui.create(dockable)

#########################################################################
#   CLASS FOR UI INPUT LIKE FOLDER PATH, PRESET NAME, RENDERER CHOICE...#
#########################################################################

class ui_input:
	
	#Rename Tab
	def renameTab(self, reset):
		global nameGrp1Glo
		global nameGrp2Glo
		global nameGrp3Glo
		
		#Reset names
		if reset == True:
			nameGrp1Glo = 'Grp1'
			cmds.tabLayout( ui.tabs, edit=True,annotation='List of presets (Group: {0} )'.format(nameGrp1Glo), tabLabel=((ui.child1, nameGrp1Glo)))
			nameGrp2Glo = 'Grp2'
			cmds.tabLayout( ui.tabs, edit=True,annotation='List of presets (Group: {0} )'.format(nameGrp2Glo), tabLabel=((ui.child2, nameGrp2Glo)))
			nameGrp3Glo = 'Grp3'
			cmds.tabLayout( ui.tabs, edit=True,annotation='List of presets (Group: {0} )'.format(nameGrp3Glo), tabLabel=((ui.child3, nameGrp3Glo)))
		#Change names	
		else:
			name = cmds.promptDialog(
	                title='Rename Current Tab',
	                message='Enter Name:',
	                button=['Ok', 'Cancel'],
	                defaultButton='Ok',
	                cancelButton='Cancel',
	                dismissString='Cancel')
			
			
			if name == "Ok":
				
				name = cmds.promptDialog(query=True, text=True)
				
				tabSelected = ui_input.tabSelected()
				
				if tabSelected == "tab0":
					nameGrp1Glo = name
					cmds.tabLayout( ui.tabs, edit=True,annotation='List of presets (Group: {0} )'.format(nameGrp1Glo), tabLabel=((ui.child1, nameGrp1Glo)))
				elif tabSelected == "tab1":
					nameGrp2Glo = name
					cmds.tabLayout( ui.tabs, edit=True,annotation='List of presets (Group: {0} )'.format(nameGrp2Glo), tabLabel=((ui.child2, nameGrp2Glo)))
				elif tabSelected == "tab2":
					nameGrp3Glo = name
					cmds.tabLayout( ui.tabs, edit=True,annotation='List of presets (Group: {0} )'.format(nameGrp3Glo), tabLabel=((ui.child3, nameGrp3Glo)))	
				else:
					return
			else:
				return
				
		
		def currentList(self, preset_name, list_of_presets, list_of_presets1, list_of_presets2):
			tabSelected = ui_input.tabSelected()
			
			if tabSelected == "tab0":
				list_of_presets = list_of_presets
			elif tabSelected == "tab1":
				list_of_presets = list_of_presets1
			elif tabSelected == "tab2":
				list_of_presets = list_of_presets2
								
			return list_of_presets
			
	# Fin current preset list from tab adn append preset
	def appendPresetList(self, preset_name, list_of_presets, list_of_presets1, list_of_presets2):
		tabSelected = ui_input.tabSelected()
		
		if tabSelected == "tab0":
			list_of_presets.append(preset_name)
				
		elif tabSelected == "tab1":
			list_of_presets1.append(preset_name)
			
		elif tabSelected == "tab2":
			list_of_presets2.append(preset_name)

		else:
			return
			
		cmds.textScrollList( ui.preset_list, edit=True, removeAll=True)
		cmds.textScrollList( ui.preset_list1, edit=True, removeAll=True)
		cmds.textScrollList( ui.preset_list2, edit=True, removeAll=True)
		
		cmds.textScrollList( ui.preset_list, edit=True, append=list_of_presets)
		cmds.textScrollList( ui.preset_list1, edit=True, append=list_of_presets1)
		cmds.textScrollList( ui.preset_list2, edit=True, append=list_of_presets2)
			
	
	# Find Tab
	def tabSelected(self):
		tabSelected = cmds.tabLayout(ui.tabs, query=True, selectTab=True)
		return tabSelected
		
	# Delete preset from tab
	def deletePresetFromTab(self,preset_selected):
			
		tabSelected=ui_input.tabSelected()
		
		if tabSelected == "tab0":
			list_of_presets.remove(preset_selected)
		elif tabSelected == "tab1":
			list_of_presets1.remove(preset_selected)
		elif tabSelected == "tab2":
			list_of_presets2.remove(preset_selected)
		else:
			return
	
	# Debug mode
	def debug(self):
		debugMode = cmds.menuItem(ui.debugOpt, query = True, checkBox = True )
		return debugMode
	
	#CheckOnlineUpdate
	def findVersion(self):
		
		try:
		
			monurl = "http://guillaumejobst.blogspot.co.uk/p/tools-version.html"
			data = urllib.urlopen(monurl).read()
		except:
			prompt = cmds.confirmDialog( title='Error', message='Connection to www.guillaume-j.com failed, check internet connection or firewall ?',
										button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
		
		
		if "ERROR" in data:
			prompt = cmds.confirmDialog( title='Error', message='Connection to www.guillaume-j.com failed, Please try again.',
										button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			return
		
		beginTag = "LPV__"
		endTag   = "__LPV"

		startPos = data.find(beginTag)
		
		while startPos > -1:
			endPos = data.find(endTag,startPos+1)
			if endTag == -1:
				break
			else:
				versionOnline = data[startPos+len(beginTag):endPos]
				print "Light Presets Latest Version is:",versionOnline
				startPos = data.find(beginTag,endPos+1)
		return versionOnline
	
	#update
	def upDate(self,script_version,versionOnline):
			
		if int(script_version.replace(".","")) < int(versionOnline.replace(".","")) :
			
			try:			
				monurl = "http://guillaumejobst.blogspot.co.uk/p/tools-version.html"
				data = urllib.urlopen(monurl).read()
			except:
				prompt = cmds.confirmDialog( title='Error', message='Connection to www.guillaume-j.com failed, check internet connection or firewall ?',
											button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			
			beginTag = "LPVM__"
			endTag  = "__MLPV"
			
			startPos = data.find(beginTag)
			
			while startPos > -1:
				endPos = data.find(endTag,startPos+1)
				if endTag == -1:
					break
				else:
					versionText = data[startPos+len(beginTag):endPos]
					startPos = data.find(beginTag,endPos+1)
			
			prompt = cmds.confirmDialog( title='Info', message= versionText + str(versionOnline),
										button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
	
		else:
			prompt = cmds.confirmDialog( title='Info', message='Script is already up to date.',
										button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
	
	#List from folder
	def listFromFolder(self,folder_path):
		
		if folder_path[0] == "None" or folder_path is None:
			confirm_del = cmds.confirmDialog( title='Error', message='Destination folder not setuped, select one', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			folder_path=ui_input.pick_a_folder()
		
		list = os.listdir(folder_path[0])
		
		for fichier in list:
			if ".xml" in fichier:
				
				try:
					xmlFile_parse = xml.parse( folder_path[0] + os.sep + fichier)	
					xmlFile_parse.getElementsByTagName('GJ_Renderer_Preset_File')
				except:
					continue
				# Find tab and append according list of preset
				if ui_input.tabSelected() == "tab0":				
					if fichier.replace(".xml","") not in list_of_presets:
						list_of_presets.append(fichier.replace(".xml",""))
				elif ui_input.tabSelected() == "tab1":				
					if fichier.replace(".xml","") not in list_of_presets1:
						list_of_presets1.append(fichier.replace(".xml",""))	
				if ui_input.tabSelected() == "tab2":				
					if fichier.replace(".xml","") not in list_of_presets2:
						list_of_presets2.append(fichier.replace(".xml",""))
			else:
				continue
		# Change the textList according the the tab name
		if ui_input.tabSelected() == "tab0":
			cmds.textScrollList( ui.preset_list, edit=True, removeAll=True)
			cmds.textScrollList( ui.preset_list, edit=True, append=list_of_presets)
		elif ui_input.tabSelected() == "tab1":
			cmds.textScrollList( ui.preset_list1, edit=True, removeAll=True)
			cmds.textScrollList( ui.preset_list1, edit=True, append=list_of_presets1)
		elif ui_input.tabSelected() == "tab2":
			cmds.textScrollList( ui.preset_list2, edit=True, removeAll=True)
			cmds.textScrollList( ui.preset_list2, edit=True, append=list_of_presets2)
	
	#Open as text
	def open_asText(self, folder_path):
		
		try:
			
			preset_selected = cmds.textScrollList(ui_input.preset_from_list() , query = True , selectItem = True )[0]
			
		except:
			confirm_del = cmds.confirmDialog( title='Error', message= 'Select a preset in the list.', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) 
			
			return
		#Open
		os.startfile(str(folder_path[0]) + os.sep + preset_selected + ".xml")
		
	#Open the folder location
	def open_folder(self):
		
		try:
			os.startfile(folder_path[0])
		except :
			errorPop = cmds.confirmDialog( title='Error', message='Folder Path not defined, do it now ?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
			if errorPop == 'Yes':
				ui_input.pick_a_folder()
				
	# Only Camera
	def saveOnlyCam(self):
		saveOnlyCameraValue = cmds.checkBox(ui.saveOnlyCamera, query=True, value=True)
		return saveOnlyCameraValue
	#Display warning
	def displayWarning(self):
		displayWarningValue = cmds.menuItem(ui.displayWarning, query = True, checkBox = True)
		return displayWarningValue
		
	#load Only Renderer
	def load_only_renderer(self):
		load_only_renderer = cmds.checkBox( ui.loadRenderer_checkbox, query = True , value = True  )
		return load_only_renderer
	
	#Delete xml
	def delete_xml(self):
		delete_xml = cmds.checkBox( ui.delete_xml_checkbox, query = True , value = True  )
		return delete_xml
	
	#Preset Name from list
	def preset_from_list(self):
		
		tabSelected = ui_input.tabSelected()
		
		if tabSelected == "tab0":
			preset_from_list = ui.preset_list
		elif tabSelected == "tab1":
			preset_from_list = ui.preset_list1
		elif tabSelected == "tab2":
			preset_from_list = ui.preset_list2
		else:
			return
			
		return preset_from_list
	
	#Preset list
	def preset_list(self):
		preset_list = ui.preset_list
		return preset_list
	
	#Only selected
	def only_selected(self):
		onlySelected_value = cmds.checkBox( ui.onlySelected, query = True , value = True  )
		return onlySelected_value
		
	#Save Renderer Param
	def save_renderer(self):
		save_renderer = cmds.checkBox( ui.saveRenderer_checkbox, query = True , value = True  )
		return save_renderer
		
	#create lights
	def create_lights(self):
		create_lights = cmds.checkBox( ui.createLights_checkbox, query = True , value = True  )
		return create_lights
		
	# Pick a folder
	def pick_a_folder(self):
		global folder_path
		
		error_pick = 0
		
		folder_path = cmds.fileDialog2(fileMode=3, caption="Select a destination folder")

		try :
			folder_path[0]
			
		except TypeError :
			
			error_pick = 1
					
			promptPath = cmds.confirmDialog( title='Error',
					message= "Pick a valid folder",
					button=['Ok'], 
					defaultButton='Ok',
					cancelButton='Ok', 
					dismissString='Ok' )	
		
		if error_pick == 1:
			return						
			
		else:
			promptPath = cmds.confirmDialog( title='Folder path is :',
				message= str(folder_path[0]),
				button=['Ok'], 
				defaultButton='Ok',
				cancelButton='Ok', 
				dismissString='Ok' )
				
			return folder_path
	
	#HELP
	def about(self):
		promptError = cmds.confirmDialog( title='About',
		message= """
                 - GJ Light Preset v b{0} -

         More infos at : www.guillaume-j.com
          Contact : contact@guillaume-j.com
			""".format(script_version),
			button=['Okay !'], 
			defaultButton='Okay !',
			cancelButton='Okay', 
			dismissString='Okay !' )		
			
	def show_help(self):
		promptError = cmds.confirmDialog( title='Help',
		message= """
                    - GJ Light Preset v{0} -
                        by Guillaume Jobst
	
How to use:
	
1 - Setup a folder where all presets will be saved
	
2 - Choose options : Only selected lights/Cameras
     Save rendering parameters, or create lights.
	    
3 - Clic "save preset", presets are simple .xml files.
	
	
More infos at : www.guillaume-j.com
Contact : contact@guillaume-j.com
			""".format(script_version),
			button=['Okay !'], 
			defaultButton='Okay !',
			cancelButton='Okay', 
			dismissString='Okay !' )
		
	# Display Folder path
	def show_path(self):
		
		self.input_folder = folder_path
		
		if self.input_folder:
			self.input_folder = self.input_folder
		else:
			self.input_folder = ['None']
		
		promptPath = cmds.confirmDialog( title='Folder path is :',
					message= str(self.input_folder[0]),
					button=['Ok'], 
					defaultButton='Ok',
					cancelButton='Ok', 
					dismissString='Ok' )

ui_input = ui_input()

#########################################################################
#   __MAIN__CLASS__PICK__DATAS__
#########################################################################

#MAIN CLASS TO FIND LIGHTING ATTRIBUTS
class LightsList :
	"""Find all attribut of lights in the scene :
	   - find_lights(self) => Find Lights parameters (MR and Vray)
	   - find_gi_mr(self) => Find MentalRay's rendering parameters
	   - find_gi_vray(self) => Find Vray's rendering parameters
	"""
	
	def __init__(self ):
		"""Default basic datas"""
		
		#Basic Datas		
		self.output_datas = ""
		
		#GI lists
		self.list_of_mentalRay_values = []	
		self.list_of_mentalRay_settings = []
		
		self.list_of_vray_settings = []
		self.list_of_vray_values = []
		
		# Camera Lists
		self.camera_list = []
		self.camera_list_attr_name = []
		self.camera_list_attr_value = []
		self.camera_xform = []
		self.camera_xform_t_values = []
		self.camera_xform_r_values = []
		self.camera_xform_s_values = []
		self.isAim = False
		self.camera_aim_xform_t_values = []
		self.camera_aim_xform_r_values = []
		self.camera_aim_xform_s_values = []
		
		# Maya lists
		self.list_of_maya_type = []
		self.list_of_full_maya_attr = []
		self.list_maya_attr = []
		self.list_maya_value = []
		self.list_of_type_maya = []
		self.maya_xform_r_values = []
		self.maya_xform_t_values = []
		self.maya_xform_s_values = []
		
		self.list_sunSky_attr = []
		self.list_sunSky_value = []
		self.list_sunSky_list = []
		
		# Vray Lists
		self.list_of_vray_type = []
		self.list_of_full_vray_attr = []
		self.list_vray_attr = []
		self.list_vray_value = []
		self.list_of_type_vray = []
		self.vray_xform_t_values = []
		self.vray_xform_r_values = []
	
	#Find Lights attributs
	def find_lights(self):
		"""Find all lights scene and transform node attributs"""
		
		#Is option save camera checked
		saveCam = cmds.checkBox(ui.saveCamera, query = True, value = True)
		savePersp = cmds.menuItem(ui.savePersp, query = True, checkBox=True)
						
		cameraAttr = ['focalLength','cameraScale','nearClipPlane','farClipPlane','horizontalFilmAperture','verticalFilmAperture','lensSqueezeRatio','filmFit',
					'filmFitOffset','horizontalFilmOffset','verticalFilmOffset','shakeEnabled','horizontalShake','verticalShake','shakeOverscanEnabled',
					'preScale','filmTranslateH','filmTranslateV','horizontalRollPivot','verticalRollPivot','filmRollValue','filmRollOrder','postScale',
					'depthOfField','focusDistance','fStop','focusRegionScale','renderable','image','depth','mask','depthType',
					'transparencyBasedDepth','transparencyBasedDepth','threshold','backgroundColor','shutterAngle','displayFilmGate',
					'displayResolution','displayGateMask','displayGateMaskColor','displayFieldChart','displayFieldChart','displaySafeTitle','displayFilmPivot',
					'displayFilmOrigin','overscan','panZoomEnabled','horizontalPan','verticalPan','zoom','renderPanZoom','journalCommand','centerOfInterest',
					'tumblePivotX','tumblePivotY','tumblePivotZ','usePivotAsLocalSpace','orthographic','orthographicWidth','visibility','template','visibility',
					'lodVisibility','locatorScale']#'shakeOverscan',
			
		cameraVrayAttrList = ['vrayCameraPhysicalOn','vrayCameraPhysicalUseMoBlur','vrayCameraPhysicalType','vrayCameraPhysicalFilmWidth','vrayCameraPhysicalFocalLength','vrayCameraPhysicalSpecifyFOV',
						'vrayCameraPhysicalFOV','vrayCameraPhysicalZoomFactor','vrayCameraPhysicalDistortionType','vrayCameraPhysicalDistortion','vrayCameraPhysicalFNumber',
						'vrayCameraPhysicalLensShift','vrayCameraPhysicalSpecifyFOV','vrayCameraPhysicalSpecifyFOV','vrayCameraPhysicalShutterAngle','vrayCameraPhysicalShutterOffset',
						'vrayCameraPhysicalISO','vrayCameraPhysicalSpecifyFocus','vrayCameraPhysicalFocusDistance','vrayCameraPhysicalExposure','vrayCameraPhysicalExposure',
						'vrayCameraPhysicalWhiteBalance','vrayCameraPhysicalVignetting','vrayCameraPhysicalVignettingAmount','vrayCameraPhysicalBladesEnable',
						'vrayCameraPhysicalBladesNum','vrayCameraPhysicalBladesRotation','vrayCameraPhysicalCenterBias','vrayCameraPhysicalAnisotropy','vrayCameraPhysicalUseDof',
						'vrayCameraPhysicalSubdivs']
						
		cameraVraySettings = ['vrayCameraOverridesOn','vrayCameraType','vrayCameraOverrideFOV','vrayCameraFOV',
							'vrayCameraAutoFit','vrayCameraDist','vrayCameraCurve']
							
		cameraVrayDome = ['vrayCameraDomeOn','vrayCameraDomeFlipX','vrayCameraDomeFlipY','vrayCameraDomeFov']
							
		allVrayAttr = []
		allVrayAttr.append(cameraVrayAttrList)
		allVrayAttr.append(cameraVraySettings)
		allVrayAttr.append(cameraVrayDome)
		
		# List camera
		if saveCam == True:
		#If only selected or not
			listOfCam = [] # Reset of the list	
		
			if ui_input.only_selected() == True:
				
				selObj = cmds.ls(selection = True)
				
				for sel in selObj:
					obj = str(cmds.listRelatives(sel , children = True))
					obj = obj.replace("[u'","").replace("']","").replace("u","").replace("'","")
					
					if cmds.objectType(obj) == 'camera':
						listOfCam.append( obj )
					
				if savePersp == True:
					listOfCam.append('perspShape')
					
			else:		
				#No only Sel		
				listOfCam = cmds.ls(type='camera')
				# With or without persp
				listOfCam.remove('frontShape')
				listOfCam.remove('sideShape')
				listOfCam.remove('topShape')
				if savePersp == False:
					listOfCam.remove('perspShape')
		else:
			listOfCam = []
				
		# Find camera xform	
		if listOfCam == []:
			self.camera_xform = []
		else:
			for cam in listOfCam :
				self.camera_xform.append(cmds.listRelatives(cam , parent = True))
				
		# Cam Translate loop		
		for i in range( 0 , len(self.camera_xform) ) :
			
			self.camera_xform_t_values.append( cmds.xform ( self.camera_xform[i] , query = True , translation = True) )
			
		# Cam rotate loop		
		for i in range( 0 , len(self.camera_xform) ) :			
			
			self.camera_xform_r_values.append( cmds.xform ( self.camera_xform[i] , query = True , rotation = True) )

		# Cam scale loop		
		for i in range( 0 , len(self.camera_xform) ) :			
			
			self.camera_xform_s_values.append( cmds.xform ( self.camera_xform[i] , query = True , scale = True) )
				
		self.camera_list = listOfCam			#Output List of cameras
		self.camera_xform = self.camera_xform	#Output List of camera xForm nodes

		#Camera Attributs find
		self.camera_list_attr_name = []
		self.camera_list_attr_value = []

		for i in range(0, len(self.camera_list)) :
			
			#Ajouter attr Camera
			
			#Test if its Vray Cam
			nameOfGroup = [".vrayCameraPhysicalOn",".vrayCameraOverridesOn",".vrayCameraDomeOn"]
			
			for name in range(0, len(allVrayAttr)) :
				try:
					phyCam = cmds.getAttr( str(self.camera_list[i]) + str(nameOfGroup[name]))

					if phyCam == 0:
						isVrayCam = False
						cameraAttr = cameraAttr
						continue
					else:
						isVrayCam = True
						cameraAttr = cameraAttr + allVrayAttr[name]
						continue
	
				except:
					isVrayCam = False
					cameraAttr = cameraAttr
					continue
					
			if ui_input.debug()	== True:
				print "DEBUG: Attr camera " + str(cameraAttr) 
			
			#Attr Name
			self.camera_list_attr_name.append(cameraAttr)
			
			tmp = []
			for ite in range (0, len(self.camera_list_attr_name[i])):

				tmp.append( cmds.getAttr ( self.camera_list[i] + "." + self.camera_list_attr_name[i][ite] ) )

			self.camera_list_attr_value.append(  tmp  )
			
		#List of maya lights		
		#If only selected or not
		if ui_input.saveOnlyCam() == True and cmds.checkBox(ui.saveCamera, query = True, value = True) == True:
			list_of_lights_maya = []
		else:
			if ui_input.only_selected() == True and cmds.getAttr ("defaultRenderGlobals.currentRenderer") != "vray":
				list_of_lights_maya = []
				selObj = cmds.ls (selection = True)
				
				for sel in selObj:
					obj = str(cmds.listRelatives(sel , children = True))
					obj = obj.replace("[u'","").replace("']","").replace("u","").replace("'","")
					
					if cmds.objectType(obj) in ['directionalLight','areaLight','pointLight','spotLight']:
						list_of_lights_maya.append( obj )
				
			# not only selected
			else:
				if cmds.getAttr ("defaultRenderGlobals.currentRenderer") == "mentalRay":
					list_of_lights_maya = cmds.ls ( type = ['light','mentalrayIblShape'])
					if 'sunShape' in list_of_lights_maya:
						list_of_lights_maya.remove('sunShape')
				else:
					list_of_lights_maya = cmds.ls (type = 'light')
				if 'sunShape' in list_of_lights_maya:
					list_of_lights_maya.remove('sunShape')
				
		#find xform
		if list_of_lights_maya == []:
			list_of_light_xform_maya = []
		else:
			list_of_light_xform_maya = cmds.listRelatives( list_of_lights_maya , parent = True )	
		
		#List of vray lights		
		if ui_input.saveOnlyCam() == True and cmds.checkBox(ui.saveCamera, query = True, value = True) == True:
			list_of_lights_vray = []
		else:
			if cmds.getAttr ("defaultRenderGlobals.currentRenderer") == "vray":
				#if only selected or not
				if ui_input.only_selected() == True:
					list_of_lights_vray = []
					selObj = cmds.ls (selection = True)
					for sel in selObj:
						obj = str(cmds.listRelatives(sel , children = True))
						obj = obj.replace("[u'","").replace("']","").replace("u","").replace("'","")
						
						if cmds.objectType(obj) in ['VRayLightSphereShape', 'VRayLightRectShape','VRayLightIESShape','VRayLightDomeShape']:					
							list_of_lights_vray.append( obj )
						
				else:
					list_of_lights_vray = cmds.ls ( type = ['VRayLightSphereShape', 'VRayLightRectShape','VRayLightIESShape','VRayLightDomeShape'] )
			else:
				if ui_input.displayWarning() == True:
					cmds.warning("Vray lights skipped if vray engine not enabled")
				list_of_lights_vray = []
					
		if list_of_lights_vray == []:
			list_of_light_xform_vray = []
			########################################
		else:
			list_of_light_xform_vray = cmds.listRelatives( list_of_lights_vray , parent = True )			

		# Maya Translate loop		
		for i in range( 0 , len(list_of_light_xform_maya) ) :
			
			self.maya_xform_t_values.append( cmds.xform ( list_of_light_xform_maya[i] , query = True , translation = True) )
			
		# Maya rotate loop		
		for i in range( 0 , len(list_of_light_xform_maya) ) :			
			
			self.maya_xform_r_values.append( cmds.xform ( list_of_light_xform_maya[i] , query = True , rotation = True) )

		# Maya scale loop		
		for i in range( 0 , len(list_of_light_xform_maya) ) :			
			
			self.maya_xform_s_values.append( cmds.xform ( list_of_light_xform_maya[i] , query = True , scale = True) )
		# Vray translate loop		
		for i in range( 0 , len(list_of_light_xform_vray) ) :
			
			self.vray_xform_t_values.append( cmds.xform ( list_of_light_xform_vray[i] , query = True , translation = True) )
	
		# Vray rotate loop		
		for i in range( 0 , len(list_of_light_xform_vray) ) :			
			
			self.vray_xform_r_values.append( cmds.xform ( list_of_light_xform_vray[i] , query = True , rotation = True) )	
		
		#Maya Attributs find	
		j = -1
		for lights in list_of_lights_maya :
			#is IBL
			if cmds.objectType(lights) == 'mentalrayIblShape':
				self.list_maya_attr.append(['texture','mapping','hardwareFilter','hardwareExposure','hardwareAlpha','colorGain','colorOffset','invert','alphaIsLuminance','primaryVisibility','visibleInEnvironment','visibleInReflections',
				'visibleInRefractions','visibleInFinalGather','overrideEnvColorFx','envInvert','envColorGain','envColorOffset','overrideFgColorFx','fgInvert','fgColorGain','fgColorOffset',
				'fgFilterSize','emitLight','filterU','filterV','samplesU','samplesV','lowSamplesU','lowSamplesV','jitter','skipBack','emitDiffuse','emitSpecular','useRayTraceShadows','shadowColor',
				'rayDepthLimit','overrideLightColorFx','lightInvert','lightColorGain','lightColorOffset','emitPhotons','globillumPhotons','causticPhotons','exponent','standardEmission',
				'overridePhotonColorFx','photonInvert','photonColorGain','photonColorOffset'])
			#is aeraLight
			elif cmds.objectType(lights) == 'areaLight':
				self.list_maya_attr.append(['color','intensity','emitDiffuse','emitSpecular','decayRate','shadowColor','useDepthMapShadows','dmapResolution','useMidDistDmap',
				'dmapFilterSize','dmapBias','fogShadowIntensity','volumeShadowSamples','useRayTraceShadows','shadowRays','rayDepthLimit','emitPhotons','areaLight','areaType',
				'areaHiSamples','areaHiSampleLimit','areaLoSamples','areaVisible','areaShapeIntensity','photonIntensity','exponent','miExportMrLight','causticPhotons','globIllPhotons'])
			#is directionalLight
			elif cmds.objectType(lights) == 'directionalLight':	
				self.list_maya_attr.append(['color','intensity','emitDiffuse','emitSpecular','shadowColor','useDepthMapShadows','dmapResolution','useMidDistDmap','useDmapAutoFocus',
				'dmapWidthFocus','useLightPosition','dmapFilterSize','dmapBias','fogShadowIntensity','volumeShadowSamples','useRayTraceShadows','lightAngle','shadowRays','rayDepthLimit',
				'emitPhotons','photonIntensity','exponent'])
			#is pointLight
			elif cmds.objectType(lights) == 'pointLight':
				self.list_maya_attr.append(['color','intensity','emitDiffuse','emitSpecular','decayRate','fogType','fogRadius','fogIntensity','shadowColor','useDepthMapShadows',
				'dmapResolution','useMidDistDmap','useDmapAutoFocus','dmapFocus','dmapFilterSize','dmapBias','fogShadowIntensity','volumeShadowSamples','useRayTraceShadows',
				'lightRadius','shadowRays','rayDepthLimit','emitPhotons','photonIntensity','exponent','causticPhotons','globIllPhotons'])
			#is spotLight
			elif cmds.objectType(lights) == 'spotLight':
				self.list_maya_attr.append(['color','intensity','emitDiffuse','emitSpecular','decayRate','coneAngle','penumbraAngle','dropoff','fogSpread','fogIntensity','barnDoors',
				'leftBarnDoor','rightBarnDoor','topBarnDoor','bottomBarnDoor','useDecayRegions','startDistance1','endDistance1','startDistance2','endDistance2','startDistance3',
				'endDistance3','shadowColor','useDepthMapShadows','dmapResolution','useMidDistDmap','useDmapAutoFocus','dmapFocus','dmapFilterSize','dmapBias','fogShadowIntensity',
				'volumeShadowSamples','useRayTraceShadows','lightRadius','shadowRays','rayDepthLimit','areaLight','areaType','areaSamplingU','areaSamplingV','areaLowLevel',
				'areaLowSamplingU','areaVisible','emitPhotons','photonIntensity','areaLowSamplingV','exponent','causticPhotons','globIllPhotons'])
			else:
				continue
			#Pick light type
			self.list_of_maya_type.append ( cmds.nodeType(lights) )
			
			tmp = []
			j += 1
			for i in range (0, len(self.list_maya_attr[j])):

				tmp.append( cmds.getAttr ( lights + "." + self.list_maya_attr[j][i] ) )

			self.list_maya_value.append(  tmp  )			
			
		self.list_sunSky_attr = []
		self.list_sunSky_value = []
		self.list_sunSky_list = []		
		
		#Name of mia physical sky and camera
		try:
			namePhySky = cmds.connectionInfo("mentalrayGlobals.sunAndSkyShader", sourceFromDestination = True)
		except:
			namePhySky = None
		if namePhySky != None:
			namePhySky = namePhySky.replace(".message","")
			
			#Test if sun and sky is connected
			try:
				listCoSky = cmds.listConnections(namePhySky)[0:7]
				isSunSkyConnected = True
			except ValueError:
				isSunSkyConnected = False
			
			if isSunSkyConnected == True:
				cameraName = listCoSky[2]
				
				self.list_sunSky_list = [cameraName,"sunDirection","mia_exposure_simple1","mia_physicalsun1","mia_physicalsky1"]
				
				j = -1 #Intermediat increment
				for obj in self.list_sunSky_list:
					
					if obj == cameraName:
						continue
						
					elif obj == 'sunDirection':
						
						self.list_sunSky_attr.append( cmds.listAttr( obj ,st = ['translateX','translateY','translateZ',
																					'rotateX','rotateY','rotateZ',
																					'scaleX','scaleY','scaleZ',
																					'rotateOrder',
																					'rotateAxisX','rotateAxisY','rotateAxisZ']))
					elif obj == 'mia_exposure_simple1':
						self.list_sunSky_attr.append( cmds.listAttr( obj ,st = ['pedestal','gain','knee','compression','gamma']))
							
					elif obj == 'mia_physicalsun1':
							
						self.list_sunSky_attr.append( cmds.listAttr( obj ,st = ['shadow_softness','samples',
																					'photon_bbox_minX','photon_bbox_minY','photon_bbox_minZ',
																					'photon_bbox_maxX','photon_bbox_maxY','photon_bbox_maxZ',
																					'automatic_photon_energy']))
					elif obj == 'mia_physicalsky1':
							
						self.list_sunSky_attr.append( cmds.listAttr( obj ,st = ['on','multiplier','rgb_unit_conversionR','rgb_unit_conversionG','rgb_unit_conversionB',
																					'haze','redblueshift','saturation','horizon_height','horizon_blur','ground_color','night_color',
																					'sun_directionY','sun_directionX','sun_directionZ','sun_disk_intensity','sun_disk_scale',
																					'sun_glow_intensity','use_background','y_is_up','flags','visibility_distance','sky_luminance_mode',
																					'zenith_luminance','diffuse_horizontal_illuminance','physically_scaled_sun']))
					
					tmp = []
					j += 1
					
					if ui_input.debug()	== True:
						print "DEBUG: " + str(self.list_sunSky_attr)
						
					for i in range (0, len(self.list_sunSky_attr[j])):
		
						tmp.append( cmds.getAttr ( obj + "." + self.list_sunSky_attr[j][i] ) )
					
					#List of sunSky Attr Values
					self.list_sunSky_value.append(  tmp  )
			else:
				cameraName = 'None'
			
		#Vray Attributs find	
		j = -1
		for lights in list_of_lights_vray :
		
			self.list_vray_attr.append( cmds.listAttr( lights ,st = ["filterColor","enabled","colorMode","lightColor","temperature","intensityMult","units","uSize","vSize","subdivs","cutoffThreshold",
																	"vrayOverrideMBSamples","vrayMBSamples","ignoreLightNormals","noDecay","doubleSided","invisible","skylightPortal",
																	"simpleSkylightPortal","storeWithIrradianceMap","affectDiffuse","affectSpecular","affectReflections","diffuseContrib",
																	"specularContrib","photonSubdivs","diffuseMult","causticsSubdivs","causticMult","locatorScale","sphereSegments",
																	"shadows","softShadows","shadowBias","shadowColor"]))
			self.list_of_vray_type.append ( cmds.nodeType(lights) )
			
			tmp = []
			j += 1
			
			for i in range (0, len(self.list_vray_attr[j]) ):
				
				tmp.append( cmds.getAttr ( lights + "." + self.list_vray_attr[j][i] ) )
					
			self.list_vray_value.append(  tmp  )
		
		#Output lists
		
		self.camera_list = self.camera_list							# Maya camera list
		self.camera_list_attr_name = self.camera_list_attr_name		# Maya Cameras attr Name
		self.camera_list_attr_value = self.camera_list_attr_value	# Maya Cameras attr Value
		self.camera_xform_t_values = self.camera_xform_t_values		# Maya Cameras xform translation
		self.camera_xform_r_values = self.camera_xform_r_values		# Maya Cameras xform rotation
		self.camera_xform_s_values = self.camera_xform_s_values		# Maya Cameras xform scale
		
		self.lights_maya = list_of_lights_maya						# Maya lights
		self.list_of_maya_type = self.list_of_maya_type				# Maya Lights Type
		self.maya_xform_t_values = self.maya_xform_t_values			# Maya lights xform translation
		self.maya_xform_r_values = self.maya_xform_r_values			# Maya lights xform rotation
		self.maya_xform_s_values = self.maya_xform_s_values			# Maya lights xform scale
		self.list_maya_attr = self.list_maya_attr	 				# Maya lights Attributs name
		self.list_maya_value = self.list_maya_value 				# Maya lights Attributs value
		
		self.list_sunSky_list = self.list_sunSky_list				# Sun and Sky nodes List
		self.list_sunSky_attr = self.list_sunSky_attr				# Sun and Sky Attr List
		self.list_sunSky_value = self.list_sunSky_value				# Sun and Sky Attr Value List
				
		self.lights_vray = list_of_lights_vray						# Vray Lights
		self.list_of_vray_type = self.list_of_vray_type				# Vray Lights Type
		self.vray_xform_t_values = self.vray_xform_t_values			# Vray Lights xform translation
		self.vray_xform_r_values = self.vray_xform_r_values			# Vray Lights xform rotation
		self.list_vray_attr = self.list_vray_attr 					# Vray lights Attributs name
		self.list_vray_value = self.list_vray_value 				# Vray lights Attributs value
			
		#Debut output datas print
		output_datas ="""
		Preset Name: {14}
		
		-----------------------------------------
		{8} Maya Light(s) Found.
		Maya Lights : {0}
		Maya Lights xform : Tr {1} Ro {12} Sc {15}
		{10} Maya lights Attributs name : {2}
		{11} Maya lights Attributs value : {3}
		-----------------------------------------
		{9} Vray Light(s) Found.
		Vray Lights : {4}
		Vray Lights xform : Tr {5} Ro {13}
		Vray lights Attributs name : {6}
		Vray lights Attributs value : {7}
		-----------------------------------------
		""".format( self.lights_maya , self.maya_xform_t_values , self.list_maya_attr , self.list_maya_value ,
					self.lights_vray , self.vray_xform_t_values , self.list_vray_attr , self.list_vray_value , 
					len(self.lights_maya) , len(self.lights_vray), len(self.list_maya_attr) , 
					len(self.list_maya_value), self.maya_xform_r_values, self.vray_xform_r_values, preset_name, self.maya_xform_s_values)
		if ui_input.debug()	== True:
			print output_datas
	
	#Find mr GI attributs
	def find_gi_mr(self, renderer_choice):
		"""Find all MentalRay Rendering attributs"""
		
		mentalRay_settings = cmds.ls('miDefaultOptions')
		
		if renderer_choice != "mentalRay":
			
			mr_error = cmds.confirmDialog( title='Error',
					message= 'MentalRay not loaded !',
					button=['Ok'], 
					defaultButton='Ok',
					cancelButton='Ok', 
					dismissString='Ok' )
		
		else:
			mentalRay_settings = cmds.ls('miDefaultOptions')
			self.list_of_mentalRay_settings = cmds.listAttr( mentalRay_settings , hasData = True , readOnly = False , st = ["*ray*","*Ray*","*finalGather*" ,"*caustic*" , "*max*" , "*globalIllum*" , "*contrast*" , "*Samples*" , "*photon*"] , visible = True )
			
			#self.mentalRay_gi_values = []
		
			for values in self.list_of_mentalRay_settings :
	
				mentalRay_gi_tmp = cmds.getAttr ( 'miDefaultOptions.' + values )
		
				self.list_of_mentalRay_values.append(str(mentalRay_gi_tmp))
				
			#Output Lists
			
			self.list_of_mentalRay_settings = self.list_of_mentalRay_settings	#List of MR attributs names
			self.list_of_mentalRay_values = self.list_of_mentalRay_values		#List of MR attributs Values
			
			output_gi_mr="""
			-----------------------------------------
			{0} Mental Ray paramters found :
			-----------------------------------------
			Names : {1}
			Values : {2}
			-----------------------------------------
			""".format( len(self.list_of_mentalRay_settings), self.list_of_mentalRay_settings, self.list_of_mentalRay_values)
			if ui_input.debug()	== True:
				print output_gi_mr		
			
	#Find vray GI attributs
	def find_gi_vray(self, renderer_choice):
		"""Find all Vray Rendering attributs"""
		
		vray_settings = cmds.ls('vraySettings')
		
		if renderer_choice != "vray":
			
			vray_error = cmds.confirmDialog( title='Error',
					message= 'MentalRay not loaded !',
					button=['Ok'], 
					defaultButton='Ok',
					cancelButton='Ok', 
					dismissString='Ok' )
		
		else:
			self.list_of_vray_settings = cmds.listAttr( vray_settings , hasData = True , readOnly = False , visible = True )
		
			for values in self.list_of_vray_settings :
	
				vray_gi_tmp = cmds.getAttr ( 'vraySettings.' + values )
		
				self.list_of_vray_values.append(str(vray_gi_tmp))
			
			#Output Lists
			
			self.list_of_vray_settings = self.list_of_vray_settings # List of Vray attributs name
			self.list_of_vray_values = self.list_of_vray_values		# List of Vray attributs Values
			
			output_gi_vray="""
			-----------------------------------------
			{0} Vray parameters found :
			-----------------------------------------
			Names : {1}
			Values : {2}
			-----------------------------------------
			""".format( len(self.list_of_vray_settings), self.list_of_vray_settings, self.list_of_vray_values)
			if ui_input.debug()	== True:
				print output_gi_vray

#ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
#WRITING DATA TO XML CLASS		
class write_data_to_xml:
	
	def __init__(self):
		"""Default values"""
		self.doc = Document()
		self.path = ""
		self.preset_name = preset_name
		
		
	def write_data(self,list_of_lights_maya, list_maya_attr, list_maya_value, list_of_maya_type,
		                list_of_lights_vray, list_vray_attr, list_vray_value, list_of_vray_type,
		                maya_xform_t_values, maya_xform_r_values,maya_xform_s_values,
		                vray_xform_t_values, vray_xform_r_values,
		                renderer_choice, list_of_vray_settings, list_of_vray_values,
		                list_of_mentalRay_settings, list_of_mentalRay_values,
		                folder,script_version,
		                list_sunSky_list,list_sunSky_attr,list_sunSky_value,
		                camera_list,camera_list_attr_name,camera_list_attr_value,
		                camera_xform_t_values,camera_xform_r_values,camera_xform_s_values):
		"""Write data in .xml file"""
		
		if folder_path[0] == "None":
			
			confirm_del = cmds.confirmDialog( title='Error', message='Destination folder not setuped, select one', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			ui_input.pick_a_folder()
		
	
		document = self.doc
		
		root_node = document.createElement("GJ_Lights_Preset_File")
		document.appendChild(root_node)
		
		version = document.createElement("Version")
		root_node.appendChild(version)
		version.setAttribute("v", script_version )
		
		# Preset name xml attribut
		name_of_preset = document.createElement("Preset")
		root_node.appendChild(name_of_preset)
		
		name_of_preset.setAttribute("name" , self.preset_name)
		
		#Maya lights datas
		if list_of_lights_maya != []:		
			lights_maya = document.createElement("___MAYA___LIGHTS___")
			root_node.appendChild(lights_maya)
			
			#Maya Lights Names
			k = 0
			j = -1
			for lights in list_of_lights_maya :
				
				lights_name_maya = document.createElement(lights)
				lights_maya.appendChild(lights_name_maya)
				
				#Maya node infos
				lights_maya_node = document.createElement("node_infos")
				lights_name_maya.appendChild(lights_maya_node)
				
				lights_maya_node.setAttribute( "name" , str(lights) )
				lights_maya_node.setAttribute( "type" , str(list_of_maya_type[k]) )				
				
				#Maya lights xform
				lights_maya_t = document.createElement("translate")
				lights_name_maya.appendChild(lights_maya_t)
				lights_maya_r = document.createElement("rotate")
				lights_name_maya.appendChild(lights_maya_r)
				lights_maya_s = document.createElement("scale")
				lights_name_maya.appendChild(lights_maya_s)	
					
				lights_maya_t.setAttribute( "t_xyz" , str(maya_xform_t_values[k]) )
				lights_maya_r.setAttribute( "r_xyz" , str(maya_xform_r_values[k]) )
				lights_maya_s.setAttribute( "s_xyz" , str(maya_xform_s_values[k]) )
				k += 1
	
				#Maya Lights Attributs			
				lights_maya_param = document.createElement("parameters")
				lights_name_maya.appendChild(lights_maya_param)
				
				j += 1
				
				for i in range (0, len(list_maya_attr[j]) ) :
					try:
						lights_maya_param.setAttribute( str(list_maya_attr[j][i]) , str(list_maya_value[j][i]))
					except IndexError:
						continue
						
						
		#Sun and Sky
		if list_sunSky_list != []:
			sunSky = document.createElement("___MR_SUN_AND_SKY___")
			root_node.appendChild(sunSky)
			
			j = -1		
			for obj in range(1, len(list_sunSky_list)):
				
				sunSky_name = document.createElement(list_sunSky_list[obj])
				sunSky.appendChild(sunSky_name)
				
				sunKy_node = document.createElement("node_infos")
				sunSky_name.appendChild(sunKy_node)				
				sunKy_node.setAttribute( "name" , str(list_sunSky_list[obj]) )
				
					
				sunSky_param = document.createElement("parameters")
				sunSky_name.appendChild(sunSky_param)	
				
				j += 1
				for i in range (0, len(list_sunSky_attr[j]) ) :
						
					sunSky_param.setAttribute( str(list_sunSky_attr[j][i]) , str(list_sunSky_value[j][i]))
		
		#Vray lights datas
		if list_of_lights_vray != []:
			lights_vray = document.createElement("___VRAY___LIGHTS___")
			root_node.appendChild(lights_vray)
			
			#Vray Lights Names
			k = 0
			j = -1
			for lights in list_of_lights_vray :
				
				#Vray node infos
				lights_name_vray = document.createElement(lights)
				lights_vray.appendChild(lights_name_vray)
				
				#Vray node infos
				lights_vray_node = document.createElement("node_infos")
				lights_name_vray.appendChild(lights_vray_node)
				
				lights_vray_node.setAttribute( "name" , str(lights) )
				lights_vray_node.setAttribute( "type" , str(list_of_vray_type[k]) )
				
				#Vray lights xform
				lights_vray_t = document.createElement("translate")
				lights_name_vray.appendChild(lights_vray_t)
				lights_vray_r = document.createElement("rotate")
				lights_name_vray.appendChild(lights_vray_r)
								
				lights_vray_t.setAttribute( "t_xyz" , str(vray_xform_t_values[k]) )
				lights_vray_r.setAttribute( "r_xyz" , str(vray_xform_r_values[k]) )
				k += 1
				#Vray Lights Attributs	
				
				lights_vray_param = document.createElement("parameters")
				lights_name_vray.appendChild(lights_vray_param)		
				
				j += 1
				
				for i in range (0, len(list_vray_attr[j]) ) :
						
					lights_vray_param.setAttribute( str(list_vray_attr[j][i]) , str(list_vray_value[j][i]))

		# Camera datas

		if camera_list != []:
			cameraDatas = document.createElement("___CAMERAS___")
			root_node.appendChild(cameraDatas)			
			#Camera Lights Names
			k = 0
			j = -1
			for cam in camera_list :
				
				#Camera node infos
				camera_name= document.createElement(cam)
				cameraDatas.appendChild(camera_name)
				
				#Camera node infos
				if 'vrayCameraPhysicalOn' in camera_list_attr_name[0]:
					typeCam = "Vray_Cam"
				else:
					typeCam = "Maya_Cam"
					
				camera_node = document.createElement("node_infos")
				camera_name.appendChild(camera_node)
				
				camera_node.setAttribute( "name" , cam )
				camera_node.setAttribute( "type" , typeCam )
				
				#Camera lights xform
				camera_t = document.createElement("translate")
				camera_name.appendChild(camera_t)
				camera_r = document.createElement("rotate")
				camera_name.appendChild(camera_r)
				camera_s = document.createElement("scale")
				camera_name.appendChild(camera_s)
								
				camera_t.setAttribute( "t_xyz" , str(camera_xform_t_values[k]) )
				camera_r.setAttribute( "r_xyz" , str(camera_xform_r_values[k]) )
				camera_s.setAttribute( "s_xyz" , str(camera_xform_s_values[k]) )
				k += 1
				#Camera Lights Attributs	
				
				camera_param = document.createElement("parameters")
				camera_name.appendChild(camera_param)		
				
				j += 1
				
				for i in range (0, len(camera_list_attr_name[j]) ) :
						
					camera_param.setAttribute( str(camera_list_attr_name[j][i]) , str(camera_list_attr_value[j][i]))			
		# GI datas
		
		# Vray
		if renderer_choice == "vray" :
			
			if list_of_vray_settings != []:
				gi_vray = document.createElement("___VRAY___GI___")
				root_node.appendChild(gi_vray)
				
				cur_renderer = 	document.createElement("VRAY")
				gi_vray.appendChild(cur_renderer)
				
				for i in range(0, len(list_of_vray_settings)) :
					
					cur_renderer.setAttribute( str(list_of_vray_settings[i]) , str(list_of_vray_values[i]) )
				
		#Mental Ray
		elif renderer_choice == "mentalRay" :
			
			if list_of_mentalRay_settings != []:

				gi_mr = document.createElement("___MENTALRAY___GI___")
				root_node.appendChild(gi_mr)
				
				cur_renderer = 	document.createElement("MENTALRAY")
				gi_mr.appendChild(cur_renderer)
				
				for i in range(0, len(list_of_mentalRay_settings)) :
					
					cur_renderer.setAttribute( str(list_of_mentalRay_settings[i]) , str(list_of_mentalRay_values[i]) )
			
		#Bad renderer
		else: 
			if ui_input.debug()	== True:
				print "Renderer not supported"
						
		# write xml file

		pathToFile = folder_path[0] + os.sep + preset_name + ".xml" 
		
		#Test is the file exist already
		if os.path.isfile(pathToFile) == True:
			warningPrompt = cmds.confirmDialog( title='Confirm',
							message='File {0} already exist in the folder, remplace ?'.format(preset_name + ".xml"), 
							button=['Yes','No (Load the existing preset in the list)'], defaultButton='Yes', cancelButton='No (Load the existing preset in the list)', dismissString='No (Load the existing preset in the list)' )
							
			if warningPrompt == 'Yes':
				xml_outpout = open(pathToFile, "w" )
				xml_outpout.write(document.toprettyxml())
				xml_outpout.close()
			else:
				return
		else:
			xml_outpout = open(pathToFile, "w" )
			xml_outpout.write(document.toprettyxml())
			xml_outpout.close()
	#Write Only Renderer	
	def write_renderer(self,renderer_choice, list_of_vray_settings, list_of_vray_values,
		                list_of_mentalRay_settings, list_of_mentalRay_values,
		                folder):
		
		if folder_path[0] == "None":
			
			confirm_del = cmds.confirmDialog( title='Error', message='Destination folder not setuped, select one', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			ui_input.pick_a_folder()	
	
		document = self.doc
		
		root_node = document.createElement("GJ_Renderer_Preset_File")
		document.appendChild(root_node)
		
		version = document.createElement("Version")
		root_node.appendChild(version)
		version.setAttribute("v", script_version )
		
		# Preset name xml attribut
		name_of_preset = document.createElement(renderer_choice + "_Preset")
		root_node.appendChild(name_of_preset)
		
		name_of_preset.setAttribute("name" , self.preset_name)
		
		# Vray
		if renderer_choice == "vray" :
			gi_vray = document.createElement("___VRAY___GI___")
			root_node.appendChild(gi_vray)
			
			cur_renderer = 	document.createElement("VRAY")
			gi_vray.appendChild(cur_renderer)
			
			for i in range(0, len(list_of_vray_settings)) :
				
				cur_renderer.setAttribute( str(list_of_vray_settings[i]) , str(list_of_vray_values[i]) )
				
		#Mental Ray
		elif renderer_choice == "mentalRay" :

			gi_mr = document.createElement("___MENTALRAY___GI___")
			root_node.appendChild(gi_mr)
			
			cur_renderer = 	document.createElement("MENTALRAY")
			gi_mr.appendChild(cur_renderer)
			
			for i in range(0, len(list_of_mentalRay_settings)) :
				
				cur_renderer.setAttribute( str(list_of_mentalRay_settings[i]) , str(list_of_mentalRay_values[i]) )
			
		#Bad renderer
		else:
			if ui_input.debug()	== True:
				print "Renderer not supported"
						
		# write xml file
		pathToFileRen = folder_path[0] +  os.sep + preset_name + "_" + renderer_choice + ".xml"
		
		#Test is the file exist already
		if os.path.isfile(pathToFileRen) == True:
			warningPrompt = cmds.confirmDialog( title='Confirm',
							message='File {0} already exist in the folder, remplace ?'.format(preset_name + "_" + renderer_choice + ".xml"), 
							button=['Yes','No (Load the existing preset in the list)'], defaultButton='Yes', cancelButton='No (Load the existing preset in the list)', dismissString='No (Load the existing preset in the list)' )
							
			if warningPrompt == 'Yes':
				xml_outpout = open(pathToFileRen, "w" )
				xml_outpout.write(document.toprettyxml())
				xml_outpout.close()
			else:
				return
		else:
			xml_outpout = open(pathToFileRen, "w" )
			xml_outpout.write(document.toprettyxml())
			xml_outpout.close()

#########################################################################
#   __CLASS__IO__WRITING__AND__READING__DATAS__ 
#########################################################################

class IO:
	
	def __init__(self):
		
		self.renderer_input = ""
		#SunSky
		self.sunSky_name_r = []
		
		#Cameras
		self.camera_name_list = []
		#Maya Lights	
		self.maya_lights_name_list = []
		self.maya_lights_type_list = []
		self.maya_lights_translate_list = []
		self.maya_lights_rotate_list = []
		self.maya_lights_attr_name_list_r = []
		self.maya_lights_attr_list_r = []
			
		#Vray Lights			
		self.vray_lights_name_list = []
		self.vray_lights_type_list = []
		self.vray_lights_translate_list = []
		self.vray_lights_rotate_list = []
		self.vray_lights_attr_name_list_r = []
		self.vray_lights_attr_list_r =[]
		
		#Output list Only Renderer
		self.is_onlyrenderer = False
		
		self.renderer_attr_value = []
		self.renderer_attr_value = []
		
		#mr output list
		self.mr_gi_name = []
		self.mr_gi_value = []
		
		#vray output list
		self.vray_gi_name = []
		self.vray_gi_value = []

	#Find renderer fonc
	def find_renderer(self):
		
		renderer_input = cmds.getAttr ("defaultRenderGlobals.currentRenderer")
		
		self.renderer_input = renderer_input		
	
	#Write data fonc
	def write(self, folder):
		
		global preset_name
		
		preset_name = "Default Preset"
		
		preset_name = cmds.promptDialog(
                title='Preset name',
                message='Enter Name:',
                button=['OK', 'Cancel'],
                defaultButton='OK',
                cancelButton='Cancel',
                dismissString='Cancel')
                
		if preset_name == 'OK':
			preset_name = cmds.promptDialog(query=True, text=True)
		else:
			return

		#Test if preset already exist
		list = cmds.textScrollList(ui_input.preset_from_list() , query = True , allItems = True )
		if list is not None :
			if preset_name in list :
				if preset_name[-1].isdigit():
					
					while preset_name in list:

						inc = int(preset_name[-1]) + 1
						
						preset_name = str(preset_name[0:-1]) + str(inc)
					
				else:
					preset_name = str(preset_name) + '1'
					
					if preset_name in list :
						if preset_name[-1].isdigit():
							
							while preset_name in list:
		
								inc = int(preset_name[-1]) + 1
								
								preset_name = str(preset_name[0:-1]) + str(inc)


		renderer_choice = cmds.getAttr ("defaultRenderGlobals.currentRenderer")		
		
		lights_finder = LightsList()		
		
		#Find Lights Attr
		lights_finder.find_lights()
		
		#Find GI attr
		if ui_input.save_renderer() == True:	
			
			if renderer_choice == "vray":
				lights_finder.find_gi_vray(renderer_choice)
				
			elif renderer_choice == "mentalRay":
				 lights_finder.find_gi_mr(renderer_choice)
		
		# Camera Data
		camera_list = lights_finder.camera_list
		camera_list_attr_name = lights_finder.camera_list_attr_name
		camera_list_attr_value = lights_finder.camera_list_attr_value
		camera_xform_t_values = lights_finder.camera_xform_t_values
		camera_xform_r_values = lights_finder.camera_xform_r_values
		camera_xform_s_values = lights_finder.camera_xform_s_values
		#Maya datas
		list_of_lights_maya = lights_finder.lights_maya
		list_maya_attr = lights_finder.list_maya_attr
		list_maya_value = lights_finder.list_maya_value
		list_of_maya_type = lights_finder.list_of_maya_type
		maya_xform_t_values = lights_finder.maya_xform_t_values
		maya_xform_r_values = lights_finder.maya_xform_r_values
		maya_xform_s_values = lights_finder.maya_xform_s_values
		
		list_sunSky_list = lights_finder.list_sunSky_list
		list_sunSky_attr = lights_finder.list_sunSky_attr
		list_sunSky_value = lights_finder.list_sunSky_value
		#Vray datas
		list_of_lights_vray = lights_finder.lights_vray
		list_vray_attr = lights_finder.list_vray_attr
		list_vray_value = lights_finder.list_vray_value
		list_of_vray_type = lights_finder.list_of_vray_type
		vray_xform_t_values = lights_finder.vray_xform_t_values
		vray_xform_r_values = lights_finder.vray_xform_r_values
		
		#Vray GI
		list_of_vray_settings = lights_finder.list_of_vray_settings
		list_of_vray_values = lights_finder.list_of_vray_values
		
		#MentalRay GI
		list_of_mentalRay_settings = lights_finder.list_of_mentalRay_settings
		list_of_mentalRay_values = lights_finder.list_of_mentalRay_values
			
		#Write Datas
		data_writter = write_data_to_xml()
		
		data_writter.write_data(list_of_lights_maya, list_maya_attr, list_maya_value, list_of_maya_type,
		                        list_of_lights_vray, list_vray_attr, list_vray_value, list_of_vray_type,
		                        maya_xform_t_values, maya_xform_r_values,maya_xform_s_values,
		                        vray_xform_t_values, vray_xform_r_values,
		                        renderer_choice, list_of_vray_settings, list_of_vray_values,
		                                         list_of_mentalRay_settings, list_of_mentalRay_values,
		                        folder_path, script_version,
		                        list_sunSky_list, list_sunSky_attr, list_sunSky_value,
		                        camera_list,camera_list_attr_name,camera_list_attr_value,
		                		camera_xform_t_values,camera_xform_r_values,camera_xform_s_values)
	
		#Append preset name to preset
		
		cmds.textScrollList(ui_input.preset_list() , edit = True , removeAll = True )	
		ui_input.appendPresetList(preset_name, list_of_presets, list_of_presets1, list_of_presets2)
		
	#Write Only Renderer Launcher
	def write_only_renderer(self):
		
		global preset_name
		
		preset_name = "Default Preset"
		
		preset_name = cmds.promptDialog(
                title='Preset name',
                message='Enter Name:',
                button=['OK', 'Cancel'],
                defaultButton='OK',
                cancelButton='Cancel',
                dismissString='Cancel')
                
		if preset_name == 'OK':
			preset_name = cmds.promptDialog(query=True, text=True)
		else:
			return
		
		#Find renderer
		renderer_choice = cmds.getAttr ("defaultRenderGlobals.currentRenderer")	
		
		lights_finder = LightsList()
		#Find Lights Attr
		lights_finder.find_lights()
		
		#Find GI attr
		if renderer_choice == "vray":
			lights_finder.find_gi_vray(renderer_choice)
				
		elif renderer_choice == "mentalRay":
			lights_finder.find_gi_mr(renderer_choice)
		
		#Vray GI
		list_of_vray_settings = lights_finder.list_of_vray_settings
		list_of_vray_values = lights_finder.list_of_vray_values
		
		#MentalRay GI
		list_of_mentalRay_settings = lights_finder.list_of_mentalRay_settings
		list_of_mentalRay_values = lights_finder.list_of_mentalRay_values
		
		data_writter_renderer = write_data_to_xml()
		
		data_writter_renderer.write_renderer(renderer_choice, list_of_vray_settings, list_of_vray_values,
		                list_of_mentalRay_settings, list_of_mentalRay_values,
		                folder_path)
		                
		#Append preset name to preset
		preset_name = preset_name + "_" + renderer_choice
		
		cmds.textScrollList(ui_input.preset_list() , edit = True , removeAll = True )	
		ui_input.appendPresetList(preset_name, list_of_presets, list_of_presets1, list_of_presets2)
		
	# ____________READING__________FONC__________	
	#Read from list
	def read_from_list(self):
		error = 0
		
		try:		
			preset_selected = cmds.textScrollList(ui_input.preset_from_list() , query = True , selectItem = True )[0]
			
		except:
			confirm_del = cmds.confirmDialog( title='Error', message= 'Select a preset in the list.', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) 
			error = 1
			return
		
		folder_path_read = folder_path[0]
		
		outputRead = ui_IO.read(preset_selected,folder_path_read)
		
		try:
			assign.assign_attr_lights(preset_selected,folder_path_read)
		
		except ValueError:
			errorPop = cmds.confirmDialog( title='Info', message='Light(s) or Camera(s) not found in the scene, create them ?', button=['Yes', 'No'], defaultButton='No', cancelButton='No', dismissString='No' )
			
			if errorPop == 'Yes':
				cmds.checkBox(ui.createLights_checkbox,edit = True, value = True )
				try:
					assign.assign_attr_lights(preset_selected,folder_path_read)
				except RuntimeError:
					cmds.confirmDialog( title='Error', message='Vray camera attributs are not supported automatically.'+"\n"+'Please add attributs manually and open the preset again.', 
											button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
				return	
					
				cmds.checkBox(ui.createLights_checkbox,edit = True, value = False )
		
			else:
				cmds.confirmDialog( title='Error', message='Importation interupted by the user', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
				return

								
		
		#check if render datas or not
		if self.renderer_data == True :
			assign.assign_attr_renderer()
			
		#Display Warning
		if ui_input.displayWarning() == True:
			cmds.warning( "Preset: " + str(preset_selected) + " loaded")
		
	#Read from file
	def read_from_file(self):
		
		error_pick = 0
		
		xml_path = cmds.fileDialog2(fileMode=1, fileFilter = "*.xml" , caption="Pick an .xml preset file")
		
		try:
			xml_path[0]
		except:
			error_pick = 1
			
		if error_pick == 0 :
			xml_path = xml_path[0]
		else:
			return
		
		xml_path_split = os.path.split(xml_path)
		
		folder_path_read = xml_path_split[0]
		preset_selected = xml_path_split[1].replace(".xml", "")
		
		ui_IO.read(preset_selected,folder_path_read)
		
		try:
			assign.assign_attr_lights(preset_selected,folder_path_read)
		
		except ValueError:
			errorPop = cmds.confirmDialog( title='Info', message='Light(s) or Camera(s) not found in the scene, create them ?', button=['Yes', 'No'], defaultButton='No', cancelButton='No', dismissString='No' )
			
			if errorPop == 'Yes':
				cmds.checkBox(ui.createLights_checkbox,edit = True, value = True )
				assign.assign_attr_lights(preset_selected,folder_path_read)
				cmds.checkBox(ui.createLights_checkbox,edit = True, value = False )
				
			else:
				cmds.confirmDialog( title='Error', message='Importation interupted by the user', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
				return		
		
		#check if render datas or not
		if self.renderer_data == True :
			assign.assign_attr_renderer()
		#Display Warning
		if ui_input.displayWarning() == True:
			cmds.warning( "Preset: " + str(preset_selected) + " loaded")
		
	#____Read fonc____
	def read(self,preset_selected,folder_path_read):
		#Init
		self.renderer_type = ""
		self.is_onlyrenderer = False
		self.is_valid = True
		self.maya_lights_name_list = []
		self.renderer_data = False
		
		#Parsing du fichier xml
		try:
			xmlFile_parse = xml.parse( folder_path_read + os.sep + preset_selected + ".xml")				
		except:
			cmds.confirmDialog( title='Error', message='ERROR: {0} is not a valid preset file.'.format(preset_selected + ".xml"), button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			return
			
		#Test if its renderer preset only
		if xmlFile_parse.getElementsByTagName('GJ_Renderer_Preset_File') != [] :
			
			self.is_onlyrenderer = True
			self.renderer_data = True
			self.renderer_attr_name = []
			self.renderer_attr_value = []
			
			# Is it Vray
			if xmlFile_parse.getElementsByTagName('vray_Preset') != [] :
				
				self.renderer_type = "vray"
				
				renderer_root = xmlFile_parse.getElementsByTagName('___VRAY___GI___')
			
			# Or MR
			elif xmlFile_parse.getElementsByTagName('mentalRay_Preset') != [] :
				
				self.renderer_type = "mr"
				
				renderer_root = xmlFile_parse.getElementsByTagName('___MENTALRAY___GI___')
			
			else:
				cmds.confirmDialog( title='Error', message='Renderer not supported ( MentalRay and Vray only supported now ).', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
				return
				
			renderer_param = renderer_root[0].childNodes[1]
			renderer_param_list = renderer_param.attributes
			
			for i in range (0, len(renderer_param_list) ):
				
				attributes = renderer_param_list.item(i)
				value = attributes.value
				name = attributes.name
				
				self.renderer_attr_value.append(	value )
				self.renderer_attr_name.append( name )
				
			if xmlFile_parse.getElementsByTagName('vray_Preset') != [] :
					
				output_gi_readed ="""
				----------------------------------
				Vray datas found :
				{0} Parameters :
				Names : {1}
				Values : {2}
				----------------------------------
				""".format( len(self.renderer_attr_value	), self.renderer_attr_name, self.renderer_attr_value	 )
				
				print output_gi_readed
				
			elif xmlFile_parse.getElementsByTagName('mentalRay_Preset') != [] :
				
				output_gi_readed ="""
				----------------------------------
				MentalRay datas found :
				{0} Parameters :
				Names : {1}
				Values : {2}
				----------------------------------
				""".format( len(self.renderer_attr_value	), self.renderer_attr_name , self.renderer_attr_value	 )
				if ui_input.debug()	== True:
					print output_gi_readed
			
			#Output list Only Renderer
			self.renderer_attr_name = self.renderer_attr_name
			self.renderer_attr_value = self.renderer_attr_value	
				
		# Test if its valid lights preset file
		elif xmlFile_parse.getElementsByTagName('GJ_Lights_Preset_File') != [] :
			current_renderer = "None"
			
			#__CAMERA__
			#Default lists
			self.camera_name_list = []
			self.camera_type_list = []
			self.camera_translate_list = []
			self.camera_rotate_list = []
			self.camera_scale_list = []
			self.camera_attr_list_r = []
			self.camera_attr_name_list_r = []
			
			camera_root = xmlFile_parse.getElementsByTagName('___CAMERAS___')
			if camera_root != []:
				
				#Puis les childs
				param = camera_root[0].childNodes
				
				#On prends que les nodes cam et pas text vides
				param = param [1::2]
				
				#Special increment
				k = 0
				#Pour chaque childs chercher les values qui correspondent
				for i in range (0 , len(param) ):
					
					childNodes = param[i].childNodes
					childNodes = childNodes[1::2]
					
					#Read Infos
					for childs in childNodes :
							
						camera_name = childNodes[0].getAttribute('name')		
						camera_type = childNodes[0].getAttribute('type')
						
					#Read Translate and rotate
					for childs in childNodes :
							
						camera_translate = childNodes[1].getAttribute('t_xyz')		
						camera_rotate = childNodes[2].getAttribute('r_xyz')
						camera_scale = childNodes[3].getAttribute('s_xyz')
					#Read Attr
					tmpList_v = []
					tmpList_n = []
						
					camera_attr_name_r = childNodes[4].attributes
						
					for i in range (0, len(camera_attr_name_r)):
							
						attributes = camera_attr_name_r.item(i)
						value = attributes.value
						name = attributes.name	
						
						tmpList_v.append(value)
						tmpList_n.append(name)		
							
					self.camera_translate_list.append(camera_translate)
					self.camera_rotate_list.append(camera_rotate)
					self.camera_scale_list.append(camera_scale)
					self.camera_name_list.append(camera_name)
					self.camera_type_list.append(camera_type)
					self.camera_attr_list_r.append(tmpList_v)
					self.camera_attr_name_list_r.append(tmpList_n)
				
					#Special increment ++
					k = k + 1
			
			#__MAYA_LIGHTS___		
			#Default lists
			self.maya_lights_name_list = []
			self.maya_lights_type_list = []
			self.maya_lights_translate_list = []
			self.maya_lights_rotate_list = []
			self.maya_lights_scale_list = []
			self.maya_lights_attr_list_r = []
			self.maya_lights_attr_name_list_r = []
			
			#Pour chaque lights maya trouver values de param
			
			#On cherche l'element MAYA LIGHTS
			maya_lights_root = xmlFile_parse.getElementsByTagName('___MAYA___LIGHTS___')
			
			if maya_lights_root != []:
				
				#Puis les childs
				param = maya_lights_root[0].childNodes
				
				#On prends que les nodes lights et pas text vides
				param = param [1::2]
				
				#Special increment
				k = 0
				#Pour chaque childs chercher les values qui correspondent
				for i in range (0 , len(param) ):
					
					childNodes = param[i].childNodes
					childNodes = childNodes[1::2]
					
					#Read Infos
					for childs in childNodes :
							
						maya_lights_name = childNodes[0].getAttribute('name')		
						maya_lights_type = childNodes[0].getAttribute('type')
						
					#Read Translate and rotate
					for childs in childNodes :
							
						maya_lights_translate = childNodes[1].getAttribute('t_xyz')		
						maya_lights_rotate = childNodes[2].getAttribute('r_xyz')
						maya_lights_scale = childNodes[3].getAttribute('s_xyz')
					#Read Attr
					tmpList_v = []
					tmpList_n = []
						
					maya_lights_attr_name_r = childNodes[4].attributes
						
					for i in range (0, len(maya_lights_attr_name_r)):
							
						attributes = maya_lights_attr_name_r.item(i)
						value = attributes.value
						name = attributes.name	
						
						tmpList_v.append(value)
						tmpList_n.append(name)		
							
					self.maya_lights_translate_list.append(maya_lights_translate)
					self.maya_lights_rotate_list.append(maya_lights_rotate)
					self.maya_lights_scale_list.append(maya_lights_scale)
					self.maya_lights_name_list.append(maya_lights_name)
					self.maya_lights_type_list.append(maya_lights_type)
					self.maya_lights_attr_list_r.append(tmpList_v)
					self.maya_lights_attr_name_list_r.append(tmpList_n)
				
					#Special increment ++
					k = k + 1
					
			#__SUN_AND_SKY___
			
			self.sunSky_name_r = []
			self.sunSky_attr_name_r = []
			self.sunSky_attr_value_r = []
			
			#On cherche l'element ___MR_SUN_AND_SKY___
			sunSky_root = xmlFile_parse.getElementsByTagName('___MR_SUN_AND_SKY___')			
			
			if sunSky_root != []:
				
				#Puis les childs
				param = sunSky_root[0].childNodes			
				#On prends que les nodes lights et pas text vides
				param = param [1::2]
				#Special increment
				k = 0
				#Pour chaque childs chercher les values qui correspondent
				for i in range (0 , len(param) ):
					
					childNodes = param[i].childNodes
					childNodes = childNodes[1::2]
					
					#Read Infos
					for childs in childNodes :
							
						sunSky_name = childNodes[0].getAttribute('name')
						
					#Read Attr
					tmpList_v = []
					tmpList_n = []
						
					sunSky_attr_name_r = childNodes[1].attributes
						
					for i in range (0, len(sunSky_attr_name_r)):
							
						attributes = sunSky_attr_name_r.item(i)
						value = attributes.value
						name = attributes.name	
						
						tmpList_v.append(value)
						tmpList_n.append(name)
						
					self.sunSky_name_r.append(sunSky_name)
					self.sunSky_attr_name_r.append(tmpList_n)
					self.sunSky_attr_value_r.append(tmpList_v)
				
			#__VRAY_LIGHTS___		
			#Default lists
			self.vray_lights_name_list = []
			self.vray_lights_type_list = []
			self.vray_lights_translate_list = []
			self.vray_lights_rotate_list = []
			self.vray_lights_attr_list_r = []
			self.vray_lights_attr_name_list_r = []
			
			#Pour chaque lights vray trouver values de param
			
			#On cherche l'element vray LIGHTS
			vray_lights_root = xmlFile_parse.getElementsByTagName('___VRAY___LIGHTS___')
			
			if vray_lights_root != []:
				
				#Puis les childs
				param = vray_lights_root[0].childNodes
				
				#On prends que les nodes lights et pas text vides
				param = param [1::2]
				
				#Special increment
				k = 0
				#Pour chaque childs chercher les values qui correspondent
				for i in range (0 , len(param) ):
					
					childNodes = param[i].childNodes
					childNodes = childNodes[1::2]
					
					#Read Infos
					for childs in childNodes :
							
						vray_lights_name = childNodes[0].getAttribute('name')		
						vray_lights_type = childNodes[0].getAttribute('type')
						
					#Read Translate and rotate
					for childs in childNodes :
							
						vray_lights_translate = childNodes[1].getAttribute('t_xyz')		
						vray_lights_rotate = childNodes[2].getAttribute('r_xyz')
						
					#Read Attr
					tmpList_v = []
					tmpList_n = []
						
					vray_lights_attr_name_r = childNodes[3].attributes
						
					for i in range (0, len(vray_lights_attr_name_r)):
							
						attributes = vray_lights_attr_name_r.item(i)
						value = attributes.value
						name = attributes.name	
						
						tmpList_v.append(value)
						tmpList_n.append(name)
						
							
					self.vray_lights_translate_list.append(vray_lights_translate)
					self.vray_lights_rotate_list.append(vray_lights_rotate)
					self.vray_lights_name_list.append(vray_lights_name)
					self.vray_lights_type_list.append(vray_lights_type)
					self.vray_lights_attr_list_r.append(tmpList_v)
					self.vray_lights_attr_name_list_r.append(tmpList_n)
				
					#Special increment ++
					k = k + 1
				
			#__GI_PARAM__
			
			mr_gi = xmlFile_parse.getElementsByTagName('___MENTALRAY___GI___')
			vray_gi = xmlFile_parse.getElementsByTagName('___VRAY___GI___')
			
			self.mr_gi_value = []
			self.mr_gi_name = []
			#Test if MR is ON
			if mr_gi != [] :
				
				self.renderer_type = "mr"
				
				mr_node = mr_gi[0].childNodes[1]
				mr_attr = mr_node.attributes
				
				tmpList_v = []
				tmpList_n = []
				
				for i in range(0,len(mr_attr)) :
					
					self.renderer_data = True
					
					attributes = mr_attr.item(i)
					value = attributes.value
					name = attributes.name	
					
					tmpList_v.append(value)
					tmpList_n.append(name)
					
				current_renderer = mr_node.tagName
				self.mr_gi_value.append(tmpList_v)
				self.mr_gi_name.append(tmpList_n)
			
			#Test if vray is ON

			elif vray_gi != []:		
				self.vray_gi_value = []
				self.vray_gi_name = []					
				self.renderer_type = "vray"


				
				vray_node = vray_gi[0].childNodes[1]
				vray_attr = vray_node.attributes
				
				tmpList_v = []
				tmpList_n = []
				
				for i in range(0,len(vray_attr)) :
					
					self.renderer_data = True
					
					attributes = vray_attr.item(i)
					value = attributes.value
					name = attributes.name	
					
					tmpList_v.append(value)
					tmpList_n.append(name)
					
				current_renderer = vray_node.tagName
				self.vray_gi_value.append(tmpList_v)
				self.vray_gi_name.append(tmpList_n)
				
			else:
				current_renderer = "None"
			#Output de debug
			output_lights_readed ="""
			
			READING OUTPUT
			----------------------------------
			{0} Maya Light(s) Found.
			Maya Lights Name: {1}
			Maya Lights Type: {2}
			Maya Lights Translate: {3}
			Maya Lights Rotate: {4}
			Maya Lights Parameters Names: {5}
			Maya Lights Parameters Values: {6}
			----------------------------------
			{7} Vray Light(s) Found.
			Vray Lights Name: {8}
			Vray Lights Type: {9}
			Vray Lights Translate: {10}
			Vray Lights Rotate: {11}
			Vray Lights Parameters Names: {12}
			Vray Lights Parameters Values: {13}
			----------------------------------
			""".format( #Maya
						len(self.maya_lights_name_list), 
						self.maya_lights_name_list,
						self.maya_lights_type_list,
						self.maya_lights_translate_list,
						self.maya_lights_rotate_list,
						self.maya_lights_attr_name_list_r,
						self.maya_lights_attr_list_r,
						#Vray
						len(self.vray_lights_name_list), 
						self.vray_lights_name_list,
						self.vray_lights_type_list,
						self.vray_lights_translate_list,
						self.vray_lights_rotate_list,
						self.vray_lights_attr_name_list_r,
						self.vray_lights_attr_list_r,
						)
						
			if current_renderer == "MENTALRAY" :
					
				output_gi_mr_readed ="""
				----------------------------------
				MentalRay datas found :
				{0} Parameters :
				Names : {1}
				Values : {2}
				----------------------------------
				""".format( len(self.mr_gi_name[0]), self.mr_gi_name, self.mr_gi_value )
				
				if ui_input.debug()	== True:
					print output_lights_readed + output_gi_mr_readed
				
				#mr output list
				self.mr_gi_name = self.mr_gi_name
				self.mr_gi_value = self.mr_gi_value
				
			elif current_renderer == "VRAY" :
				
				output_gi_vray_readed ="""
				----------------------------------
				Vray datas found :
				{0} Parameters :
				Names : {1}
				Values : {2}
				----------------------------------
				""".format( len(self.vray_gi_name[0]), self.vray_gi_name, self.vray_gi_value )
				if ui_input.debug()	== True:
					print output_lights_readed + output_gi_vray_readed
				
				#vray output list
				self.vray_gi_name = self.vray_gi_name
				self.vray_gi_value = self.vray_gi_value
			
			else :
				if ui_input.debug()	== True:
					print output_lights_readed + "No proper renderer datas found."			
			
		else:
			confirm_del = cmds.confirmDialog( title='Error', message= folder_path[0] + preset_selected + 'This file is not a valid preset xml file', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
			self.is_valid = False			
		
	#Delete preset from list
	def delete_preset(self, list_of_presets, folder_path, all):
		
		if all == False:
			
			list = cmds.textScrollList(ui_input.preset_from_list() , query = True , allItems = True )			
			if list == None:
				return
			
			# DELETE ONLY SELECTED
			try:
				preset_selected = cmds.textScrollList(ui_input.preset_from_list() , query = True , selectItem = True )[0]
			except:
				cmds.confirmDialog( title='Error', message='Select a preset in the list', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
				return
			
			#Test if delete file is ON
			delete_xml = ui_input.delete_xml()
			
			if delete_xml == True :
				confirm_del = cmds.confirmDialog( title='Confirm', message= folder_path[0] + preset_selected + '.xml file will be deleted, confirm ?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
				
				if confirm_del == 'Yes':
					
					#Test if the xml exist
					to_delete = folder_path[0] + os.sep + preset_selected + ".xml"
					file = os.access(to_delete, os.F_OK)
					
					if file == False :
						
						confirm_del = cmds.confirmDialog( title='Error', message= folder_path[0] + preset_selected + 'xml preset file not found !', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) 
					
					else :
						os.remove(to_delete)
					
						cmds.textScrollList(ui_input.preset_from_list() , edit = True , removeItem = str(preset_selected) )
						
						#Delete preset fonc
						ui_input.deletePresetFromTab(preset_selected)
						
						#Display Warning
						if ui_input.displayWarning() == True:
							cmds.warning( "Preset: " + to_delete + " Deleted !")
					
				else : pass
				
			else :
				
				cmds.textScrollList(ui_input.preset_from_list() , edit = True , removeItem = str(preset_selected) )	
				
				#Delete Preset Fonc
				ui_input.deletePresetFromTab(preset_selected)
				
				#Display Warning
				if ui_input.displayWarning() == True:
					cmds.warning( "Preset: " + preset_selected + " Deleted ( xml file not deleted )")	
				
		else:
			# DELETE ALL
			tabSelected = ui_input.tabSelected()
			
			if tabSelected == "tab0":
				list_of_presets_tmp = list_of_presets
			elif tabSelected == "tab1":
				list_of_presets_tmp = list_of_presets1
			elif tabSelected == "tab2":
				list_of_presets_tmp = list_of_presets2
						
			list = cmds.textScrollList(ui_input.preset_from_list() , query = True , allItems = True )			
			if list == None:
				return

			#Test if delete file is ON
			delete_xml = ui_input.delete_xml()
			
			if delete_xml == True :
				confirm_del = cmds.confirmDialog( title='Confirm', message= 'Delete all xml preset file from the list in folder: ' +folder_path[0] + ', confirm ?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
					
				if confirm_del == 'Yes':
					while list_of_presets_tmp != []:
				
						for preset_selected in list_of_presets_tmp :
							
							try:
								xmlFile_parse = xml.parse( folder_path[0] + os.sep + preset_selected + ".xml")	
								xmlFile_parse.getElementsByTagName('GJ_Renderer_Preset_File')
							except:
								continue
	
							#Test if the xml exist
							to_delete = folder_path[0] + os.sep + preset_selected + ".xml"
							file = os.access(to_delete, os.F_OK)
								
							if file == False :
									
								confirm_del = cmds.confirmDialog( title='Error', message= folder_path[0] + preset_selected + 'xml preset file not found !', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )							
								
							else :
								
								os.remove(to_delete)
								
								cmds.textScrollList(ui_input.preset_from_list() , edit = True , removeItem = str(preset_selected) )
								
								#Delete Preset Fonc
								ui_input.deletePresetFromTab(preset_selected)
								
								#Display Warning
								if ui_input.displayWarning() == True:					
									cmds.warning( "Preset: " + preset_selected + " Deleted !")
			else :
				
				while list_of_presets_tmp != []:
					for preset_selected in list_of_presets_tmp :
						
						cmds.textScrollList(ui_input.preset_from_list() , edit = True , removeItem = str(preset_selected) )	
						#Delete Preset Fonc
						ui_input.deletePresetFromTab(preset_selected)
						#Display Warning
						if ui_input.displayWarning() == True:
							cmds.warning( "Preset: " + to_delete + " Deleted ( xml file not deleted )")	
						
#Launch IO
ui_IO = IO()

#########################################################################
#   __CLASS__IO__ASSIGN_ATTR_and_CREATE_LIGHTS__
#########################################################################		
class AssignPreset:
	
	def __init__(self):
		
		self.maya_lights_created_list = []
		self.vray_lights_created_list = []
	
	#Assign preset fonc
	def assign_preset(self,preset_selected, folder_path_read):
		"""Assign all preset attributs to lights"""
		
		create_light_switch = ui_input.create_lights()
		
		#Import List of Objects
		maya_lights_name_list = ui_IO.maya_lights_name_list
		vray_lights_name_list = ui_IO.vray_lights_name_list
		sunSky_name_list 	  = ui_IO.sunSky_name_r
		camera_name_list 	  = ui_IO.camera_name_list

		if create_light_switch == True:
			
			lights_created = assign.create_lights(preset_selected, folder_path_read)
						
			maya_lights_name_list = lights_created[0]
			vray_lights_name_list = lights_created[1]
			camera_name_list = lights_created[2]
				
		if ui_input.debug()	== True:	
			print "DEBUG: " + str(maya_lights_name_list) + " READED"
			print "DEBUG: " + str(vray_lights_name_list) + " READED"
		
		return [maya_lights_name_list, vray_lights_name_list, sunSky_name_list, camera_name_list]
	
	#Assign Attr____
	def assign_attr_lights(self, preset_selected,folder_path_read):
		"""Assign lights attributs"""
		
		translateList = ['translateX', 'translateY', 'translateZ']
		rotateList = ['rotateX', 'rotateY', 'rotateZ']
		scaleList = ['scaleX', 'scaleY', 'scaleZ']
		
		#Import Lights list
		lights_list = assign.assign_preset(preset_selected,folder_path_read)
	
		maya_lights_name_list = lights_list[0]
		vray_lights_name_list = lights_list[1]
		sunSky_name_list      = lights_list[2]
		camera_name_list	  = lights_list[3]
		
		#Attribut Sun and sky
		li = 0
		for inc in range(0, len(ui_IO.sunSky_name_r)):
			
			for i in range( 0, len( ui_IO.sunSky_attr_name_r[li] )):
				
				#Test if its a number
				if ui_IO.sunSky_attr_value_r[li][i][0].isdigit():
					
					if "." in ui_IO.sunSky_attr_value_r[li][i]:
						value = float(ui_IO.sunSky_attr_value_r[li][i])

					else:
						value = int(ui_IO.sunSky_attr_value_r[li][i])

					cmds.setAttr( sunSky_name_list[inc] + "." + ui_IO.sunSky_attr_name_r[li][i], value )
					
				elif ui_IO.sunSky_attr_value_r[li][i][0] == "-" :
					
					if "." in ui_IO.sunSky_attr_value_r[li][i]:
						value = float(ui_IO.sunSky_attr_value_r[li][i])

					else:
						value = int(ui_IO.sunSky_attr_value_r[li][i])
					
					cmds.setAttr( sunSky_name_list[inc] + "." + ui_IO.sunSky_attr_name_r[li][i], value )
						
				elif "[" in ui_IO.sunSky_attr_value_r[li][i] :
					value = ui_IO.sunSky_attr_value_r[li][i].replace("[(", "").replace(")]", "").split(",")
					try:
						value = ( float(value[0]),float(value[1]), float(value[2]) )
						cmds.setAttr(sunSky_name_list[inc] + "." + ui_IO.sunSky_attr_name_r[li][i] , value[0],value[1],value[2], type='double3', lock = False, alteredValue =True)
					except IndexError:
						value = ( float(value[0]),float(value[1]) )
						cmds.setAttr(sunSky_name_list[inc] + "." + ui_IO.sunSky_attr_name_r[li][i] , value[0],value[1], type='double2', lock = False, alteredValue =True)					
				
				elif ui_IO.sunSky_attr_value_r[li][i] == "True":
					cmds.setAttr( sunSky_name_list[inc] + "." + ui_IO.sunSky_attr_name_r[li][i], 1 )
					
				elif ui_IO.sunSky_attr_value_r[li][i] == "False":
					cmds.setAttr( sunSky_name_list[inc] + "." + ui_IO.sunSky_attr_name_r[li][i], 0 )					
				
				#others
				else:
					continue			
			li +=1		

		#Find xForm node camera
		camera_xform_list = []
		
		if ui_input.debug()	== True:
			print "DEBUG: Camera name list found is " +str(camera_name_list)
		
		for cam in camera_name_list:
			
			camera_xform = cmds.listRelatives( cam , parent = True )
			camera_xform_list.append(camera_xform)
			
		order = 0
		for node in camera_xform_list :
			
			tr_datas = ui_IO.camera_translate_list[order].replace("[", "").replace("]","").split(",")
			rr_datas = ui_IO.camera_rotate_list[order].replace("[", "").replace("]","").split(",")
			sr_datas = ui_IO.camera_scale_list[order].replace("[", "").replace("]","").split(",")
			
			for i in range (0,3) :
				#Test if it's locked or not
				try:				
					cmds.setAttr( node[0] + "." + str(rotateList[i]), float(rr_datas[i]) )
					cmds.setAttr( node[0] + "." + str(translateList[i]), float(tr_datas[i]) )
					cmds.setAttr( node[0] + "." + str(scaleList[i]), float(sr_datas[i]) )
				except RuntimeError:
					warn = cmds.confirmDialog( title='Warning', message='This camera has a non-supported look at constrain, create a new free camera from preset ?', 
										button=['Yes','No (Skip import)'], defaultButton='Yes',
										cancelButton='No (Skip import)', dismissString='No (Skip import)' )
					if warn == 'Yes':
						
						aimTmp = cmds.listRelatives(node[0], parent=True)[0]
						cmds.delete(aimTmp)

						tmp = cmds.createNode('camera', name=camera_name_list[order])
						camCreated = cmds.listRelatives(tmp, parent=True)[0]
						
						cmds.setAttr( camCreated + "." + str(rotateList[i]), float(rr_datas[i]) )
						cmds.setAttr( camCreated + "." + str(translateList[i]), float(tr_datas[i]) )
						cmds.setAttr( camCreated + "." + str(scaleList[i]), float(sr_datas[i]) )
					else:
						cmds.confirmDialog( title='info', message='Importation canceled by the user', 
										button=['Ok'], defaultButton='Ok',
										cancelButton='Ok', dismissString='Ok' )
						return
			order += 1
		
		#Attribut camera
		li = 0
		for cam in ui_IO.camera_name_list:
			
			for i in range (0, len(ui_IO.camera_attr_name_list_r[li])) :
				
				#Test if its a number
				if ui_IO.camera_attr_list_r[li][i][0].isdigit():
					
					if "." in ui_IO.camera_attr_list_r[li][i]:
						value = float(ui_IO.camera_attr_list_r[li][i])

					else:
						value = int(ui_IO.camera_attr_list_r[li][i])

					cmds.setAttr( cam + "." + ui_IO.camera_attr_name_list_r[li][i], value )
					
				elif ui_IO.camera_attr_list_r[li][i][0] == "-" :
					
					if "." in ui_IO.camera_attr_list_r[li][i]:
						value = float(ui_IO.camera_attr_list_r[li][i])

					else:
						value = int(ui_IO.camera_attr_list_r[li][i])
					
					cmds.setAttr( cam + "." + ui_IO.camera_attr_name_list_r[li][i], value )
						
				elif "[" in ui_IO.camera_attr_list_r[li][i] :
					value = ui_IO.camera_attr_list_r[li][i].replace("[(", "").replace(")]", "").split(",")
					try:
						value = ( float(value[0]),float(value[1]), float(value[2]) )
						cmds.setAttr(cam + "." + ui_IO.camera_attr_name_list_r[li][i] , value[0],value[1],value[2], type='double3', lock = False, alteredValue =True)
					except IndexError:
						value = ( float(value[0]),float(value[1]) )
						cmds.setAttr(cam + "." + ui_IO.camera_attr_name_list_r[li][i] , value[0],value[1], type='double2', lock = False, alteredValue =True)					
				
				elif ui_IO.camera_attr_list_r[li][i] == "True":
					cmds.setAttr( cam + "." + ui_IO.camera_attr_name_list_r[li][i], 1 )
					
				elif ui_IO.camera_attr_list_r[li][i] == "False":
					cmds.setAttr( cam + "." + ui_IO.camera_attr_name_list_r[li][i], 0 )					
				
				#others
				else:
					continue			
			li +=1		

		#Find xForm node maya
		maya_lights_xform_list = []
		for lights in maya_lights_name_list:
			
			maya_lights_xform = cmds.listRelatives( lights , parent = True )
			maya_lights_xform_list.append(maya_lights_xform)
			
		order = 0
		for node in maya_lights_xform_list :
			
			tr_datas = ui_IO.maya_lights_translate_list[order].replace("[", "").replace("]","").split(",")
			rr_datas = ui_IO.maya_lights_rotate_list[order].replace("[", "").replace("]","").split(",")
			sr_datas = ui_IO.maya_lights_scale_list[order].replace("[", "").replace("]","").split(",")
			
			for i in range (0,3) :				
				cmds.setAttr( node[0] + "." + str(rotateList[i]), float(rr_datas[i]) )
				
			for i in range (0,3) :	
				cmds.setAttr( node[0] + "." + str(translateList[i]), float(tr_datas[i]) )

			for i in range (0,3) :	
				cmds.setAttr( node[0] + "." + str(scaleList[i]), float(sr_datas[i]) )		
			
			order += 1
		
		#Attribut lights Maya
		li = 0
		for lights in ui_IO.maya_lights_name_list:
			
			for i in range (0, len(ui_IO.maya_lights_attr_name_list_r[li])) :
				
				#Test if its a number
				if ui_IO.maya_lights_attr_list_r[li][i][0].isdigit():
					
					if "." in ui_IO.maya_lights_attr_list_r[li][i]:
						value = float(ui_IO.maya_lights_attr_list_r[li][i])

					else:
						value = int(ui_IO.maya_lights_attr_list_r[li][i])

					cmds.setAttr( lights + "." + ui_IO.maya_lights_attr_name_list_r[li][i], value )
					
				elif ui_IO.maya_lights_attr_list_r[li][i][0] == "-" :
					
					if "." in ui_IO.maya_lights_attr_list_r[li][i]:
						value = float(ui_IO.maya_lights_attr_list_r[li][i])

					else:
						value = int(ui_IO.maya_lights_attr_list_r[li][i])
					
					cmds.setAttr( lights + "." + ui_IO.maya_lights_attr_name_list_r[li][i], value )
						
				elif "[" in ui_IO.maya_lights_attr_list_r[li][i] :
					value = ui_IO.maya_lights_attr_list_r[li][i].replace("[(", "").replace(")]", "").split(",")
					try:
						value = ( float(value[0]),float(value[1]), float(value[2]) )
						cmds.setAttr(lights + "." + ui_IO.maya_lights_attr_name_list_r[li][i] , value[0],value[1],value[2], type='double3', lock = False, alteredValue =True)
					except IndexError:
						value = ( float(value[0]),float(value[1]) )
						cmds.setAttr(lights + "." + ui_IO.maya_lights_attr_name_list_r[li][i] , value[0],value[1], type='double2', lock = False, alteredValue =True)					
				
				elif ui_IO.maya_lights_attr_list_r[li][i] == "True":
					cmds.setAttr( lights + "." + ui_IO.maya_lights_attr_name_list_r[li][i], 1 )
					
				elif ui_IO.maya_lights_attr_list_r[li][i] == "False":
					cmds.setAttr( lights + "." + ui_IO.maya_lights_attr_name_list_r[li][i], 0 )					
				
				#others
				else:
					continue			
			li +=1		
			
		#Find xForm node vray
		vray_lights_xform_list = []
		for lights in vray_lights_name_list:
			vray_lights_xform = cmds.listRelatives( lights , parent = True )
			vray_lights_xform_list.append(vray_lights_xform)

		order = 0
		for node in vray_lights_xform_list :
			
			tr_datas = ui_IO.vray_lights_translate_list[order].replace("[", "").replace("]","").split(",")
			rr_datas = ui_IO.vray_lights_rotate_list[order].replace("[", "").replace("]","").split(",")
			
			for i in range (0,3) :				
				cmds.setAttr( node[0] + "." + str(rotateList[i]), float(rr_datas[i]) )
				
			for i in range (0,3) :	
				cmds.setAttr( node[0] + "." + str(translateList[i]), float(tr_datas[i]) )
			
			order += 1			
		
		#Attribut lights vray
		li = 0
		for lights in ui_IO.vray_lights_name_list:
			
			for i in range (0, len(ui_IO.vray_lights_attr_name_list_r[li])) :
				
				#Test if its a number
				if ui_IO.vray_lights_attr_list_r[li][i][0].isdigit():
					
					if "." in ui_IO.vray_lights_attr_list_r[li][i]:
						value = float(ui_IO.vray_lights_attr_list_r[li][i])

					else:
						value = int(ui_IO.vray_lights_attr_list_r[li][i])
						
					cmds.setAttr( lights + "." + ui_IO.vray_lights_attr_name_list_r[li][i], value )
					
				elif ui_IO.vray_lights_attr_list_r[li][i][0] == "-" :
					
					if "." in ui_IO.vray_lights_attr_list_r[li][i]:
						value = float(ui_IO.vray_lights_attr_list_r[li][i])

					else:
						value = int(ui_IO.vray_lights_attr_list_r[li][i])
						
					cmds.setAttr( lights + "." + ui_IO.vray_lights_attr_name_list_r[li][i], value )
						
				elif "[" in ui_IO.vray_lights_attr_list_r[li][i] :
					value = ui_IO.vray_lights_attr_list_r[li][i].replace("[(", "").replace(")]", "").split(",")
				
					value = ( float(value[0]),float(value[1]), float(value[2]) )
					
					cmds.setAttr(lights + "." + ui_IO.vray_lights_attr_name_list_r[li][i] , value[0],value[1],value[2], type='double3', lock = False, alteredValue =True)
				
				elif ui_IO.vray_lights_attr_list_r[li][i] == "True":
					cmds.setAttr( lights + "." + ui_IO.vray_lights_attr_name_list_r[li][i], 1 )
					
				elif ui_IO.vray_lights_attr_list_r[li][i] == "False":
					cmds.setAttr( lights + "." + ui_IO.vray_lights_attr_name_list_r[li][i], 0 )					
				
				#others
				else:
					continue
				
			li +=1
	
	def assign_attr_renderer(self):
		"""Assign renderer attributs"""
		
		#is renderer datas
		isData = ui_IO.renderer_data
		
		if isData == False :
			print "No Renderer parameters loaded"
		else:
			
			#VRAY
			if ui_IO.renderer_type == "vray":
				
				#test if vray is on
				currentRender = cmds.getAttr ("defaultRenderGlobals.currentRenderer")	
				
				if currentRender != "vray" :
					errorPop = cmds.confirmDialog( title='Indo', message='Vray parameters found in the preset, switch to vray now ?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
					
					if errorPop == "Yes":
						cmds.setAttr ("defaultRenderGlobals.currentRenderer", "vray", type = "string")
					else:
						return
						
				#Try if its only renderer or normal preset				
				if ui_IO.is_onlyrenderer == False:
					name = ui_IO.vray_gi_name[0]
					value = ui_IO.vray_gi_value[0]
				else:
					name = ui_IO.renderer_attr_name
					value = ui_IO.renderer_attr_value
				
				for i in range(0, len(name)) :
					
					if len(value[i]) == 0 :
						continue
					
					#Test if its a number
					elif value[i][0].isdigit():
						
						if "." in value[i]:
							val = float(value[i])
	
						else:
							val = int(value[i])
							
						cmds.setAttr( "vraySettings." + str(name[i] ), val )
						
					elif value[i][0] == "-" :
						
						if "." in value[i]:
							val = float(value[i])
	
						else:
							val = int(value[i])
							
						cmds.setAttr( "vraySettings." + str(name[i] ), val )
							
					elif "[(" in value[i] :
						
						if value[i] != "[()]" :
							val = value[i].replace("[(", "").replace(")]", "").split(",")
						
							val = ( float(val[0]),float(val[1]), float(val[2]) )
							
							cmds.setAttr( "vraySettings." + str(name[i] ) , val[0],val[1],val[2], type='double3')
						else:
							continue
						
					elif value[i] == "True" :
						cmds.setAttr( "vraySettings." + str(name[i] ), 1 )
						
					elif value[i] == "False" :
						cmds.setAttr( "vraySettings." + str(name[i] ), 0 )
						
					#Test if its a boolean
					else:
						continue
				if ui_input.debug()	== True:
					print """
				{0} Vray parameters loaded:
				{1}			
				""".format(len(name), str(name).replace("[u", "" ).replace(" u", "").replace("]", "") )

			#MENTAL RAY
			elif ui_IO.renderer_type == "mr":
				
				#test if mr is on
				currentRender = cmds.getAttr ("defaultRenderGlobals.currentRenderer")	
				
				if currentRender != "mentalRay" :
					errorPop = cmds.confirmDialog( title='Indo', message='Mental Ray parameters found in the preset, switch to Mental Ray now ?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
					
					if errorPop == "Yes":
						cmds.setAttr ("defaultRenderGlobals.currentRenderer", "mentalRay", type = "string")
					else:
						return
				
				#Try if its only renderer or normal preset				
				if ui_IO.is_onlyrenderer == False:
					name = ui_IO.mr_gi_name[0]
					value = ui_IO.mr_gi_value[0]
				else:
					name = ui_IO.renderer_attr_name
					value = ui_IO.renderer_attr_value
					
				for i in range(0, len(name)) :					
					
					if name[i] == "finalGatherFilename":
						continue
						
					elif name[i] == "photonMapFilename" :
						continue
						
					elif name[i] == "finalGatherImportance":
						continue
						
					if len(name[i]) == 0:
						continue
					
					#Test if its a number
					elif value[i][0].isdigit():
						
						if "." in value[i]:
							val = float(value[i])
							cmds.setAttr( "miDefaultOptions." + str(name[i]), val )
	
						else:
							val = int(value[i])							
							cmds.setAttr( "miDefaultOptions." + str(name[i]), val )
							
					elif value[i][0] == "-" :
							
						if "." in value[i]:
							val = float(value[i])
							cmds.setAttr( "miDefaultOptions." + str(name[i]), val )
	
						else:
							val = int(value[i])							
							cmds.setAttr( "miDefaultOptions." + str(name[i]), val )
							
					elif "[(" in value[i] :
						
						if value[i] != "[()]" :
							val = value[i].replace("[(", "").replace(")]", "").split(",")
						
							val = ( float(val[0]),float(val[1]), float(val[2]) )
							
							cmds.setAttr( "miDefaultOptions." + str(name[i]) , val[0],val[1],val[2], type='double3')
						else:
							continue
						
					#Test if its a boolean
					elif value[i] == "True":
						
						cmds.setAttr( "miDefaultOptions." + str(name[i]), 1 )
						
					elif value[i] == "False":
						
						cmds.setAttr( "miDefaultOptions." + str(name[i]), 0 )
					
					else:
						val = value[i]
						cmds.setAttr( "miDefaultOptions." + str(name[i]), val )
						
				if ui_input.debug()	== True:
					print """
				MentalRay parameters loaded:
				{1}			
				""".format(len(name), str(name).replace("[u", "" ).replace(" u", "").replace("]", "") )	
	
	#Create lights fonc
	def create_lights(self,preset_selected, folder_path_read):
		"""Create lights"""
		
		maya_lights_name_list = ui_IO.maya_lights_name_list
		maya_lights_type_list = ui_IO.maya_lights_type_list
		vray_lights_name_list = ui_IO.vray_lights_name_list
		vray_lights_type_list = ui_IO.vray_lights_type_list
		camera_name_list	  = ui_IO.camera_name_list
		camera_type_list	  = ui_IO.camera_type_list

		#--------SUN AND SKY-----------
		#Test if sunlight is here
		sunSkyPreset = False
		sunSkyScene = False
		#In scene
		try:
			if cmds.connectionInfo("mentalrayGlobals.sunAndSkyShader", isDestination = True) == True:
				sunSkyScene = True
		except ValueError:
			pass
		#In preset file
		if ui_IO.sunSky_name_r != []:
			sunSkyPreset = True
		
		if sunSkyPreset == True:
			
			if sunSkyScene == True:
				prompt = cmds.confirmDialog( title='Confirm', message='Sun and Sky already found in the scene, delete it ?', 
											button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
				if prompt == 'Yes':#Delete sunsky
					maya.mel.eval("miDeleteSunSky;")
					
					maya.mel.eval("miCreateSunSky;")
					
				else:
					prompt = cmds.confirmDialog( title='Cancel', message='Importation canceled by user', 
											button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' )
					return
			else:
				maya.mel.eval("miCreateSunSky;")
				
		#--------CAMERA-----------	
		camera_created = []
		camera_created_list = []
		
		#Create cam
		for i in range(0, len(camera_name_list)):
			#Skip persp
			if camera_name_list[i] == "perspShape":
				continue

			#Test if exist
			if cmds.objExists(camera_name_list[i]) == True:
			
				prompt = cmds.confirmDialog( title='Confirm', message= camera_name_list[i] +' Already in scene, delete ?', 
									button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
									
				if prompt == "Yes" :
					
					xform_ = cmds.listRelatives( camera_name_list[i] , parent = True )
					cmds.delete(camera_name_list[i])
					cmds.delete(xform_)
					camera_created = cmds.createNode( 'camera', name = camera_name_list[i] )	
				else:
					camera_created = camera_name_list[i]
					
				camera_created_list.append(camera_created)
				
			else:
				camera_created = cmds.createNode( 'camera', name = camera_name_list[i] )
						
				camera_created_list.append(camera_created)
			
		# ---- LIGHTS ----
		maya_light_created_list = []
		vray_light_created_list = []
		#Create lights		
		for i in range (0, len(maya_lights_name_list)):
					
			#Test if Maya light is already here
			if cmds.objExists(maya_lights_name_list[i]) == True:
			
				prompt = cmds.confirmDialog( title='Confirm', message= maya_lights_name_list[i] +' Already in scene, delete ?', 
									button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
									
				if prompt == "Yes" :
					
					xform_ = cmds.listRelatives( maya_lights_name_list[i] , parent = True )
					cmds.delete(maya_lights_name_list[i])
					cmds.delete(xform_)
					
					#IBL creation
					if maya_lights_type_list[i] == 'mentalrayIblShape':
						maya_light_created = cmds.createNode( maya_lights_type_list[i], name = maya_lights_name_list[i] )
						cmds.connectAttr( maya_lights_name_list[i]+'.message', 'mentalrayGlobals.imageBasedLighting' )
						
					else:
						maya_light_created = cmds.createNode( maya_lights_type_list[i], name = maya_lights_name_list[i] )
					
				else:
					maya_light_created = maya_lights_name_list[i]
					
				maya_light_created_list.append(maya_light_created)
				
			else:
				if maya_lights_type_list[i] == 'mentalrayIblShape':
						maya_light_created = cmds.createNode( maya_lights_type_list[i], name = maya_lights_name_list[i] )
						cmds.connectAttr( maya_lights_name_list[i]+'.message', 'mentalrayGlobals.imageBasedLighting' )
						
				else:
					maya_light_created = cmds.createNode( maya_lights_type_list[i], name = maya_lights_name_list[i] )
						
				maya_light_created_list.append(maya_light_created)
			
		for i in range (0, len(vray_lights_name_list)):
			
			#Test if Vray light is already here
			if cmds.objExists(vray_lights_name_list[i]):
				
				prompt = cmds.confirmDialog( title='Confirm', message= vray_lights_name_list[i] +' Already in scene, delete ?', 
									button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
				
				if prompt == "Yes" :
					
					xform_ = cmds.listRelatives( vray_lights_name_list[i] , parent = True )
					cmds.delete(vray_lights_name_list[i])
					cmds.delete(xform_)
			
					vray_light_created = cmds.createNode( vray_lights_type_list[i], name = vray_lights_name_list[i] )
				else:
					vray_light_created = vray_lights_name_list[i]
				
				vray_light_created_list.append(vray_light_created)
				
			else:
				vray_light_created = cmds.createNode( vray_lights_type_list[i], name = vray_lights_name_list[i] )				
				vray_light_created_list.append(vray_light_created)			
		
		creation_output="""
		----------------------------------
		{0} Maya Light(s) created :
		{1}
		----------------------------------
		{2} Vray Light(s) created :
		{3}
		----------------------------------
		""".format(len(maya_lights_name_list), maya_lights_name_list, len(vray_lights_name_list), vray_lights_name_list )
		
		if ui_input.debug()	== True:
			print creation_output
		
		return [maya_light_created_list, vray_light_created_list,camera_created_list]
		
# Lounch AssignPreset class
assign = AssignPreset()