# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
	'name': 'DPFR Collection Utilities',
	'author': 'Duarte Farrajota Ramos',
	'version': (3, 0, 0),
	'blender': (4, 00, 0),
	'location': 'View3D > Object > Collections and View3D > Object > Make Links',
	'description': 'Myriad of collection management utilities',
	'warning': '',
	'doc_url': 'http://addons.duarteramos.pt/#Collection%20Utilities%20Addon',
	'category': 'Collection',
}


import bpy
from bpy.props import StringProperty, EnumProperty, IntProperty, BoolProperty, FloatProperty

#############################################################################################
# Operators

##############################################
## Sets collection instance offset from object
class COLLECTION_OT_OffsetFromObject(bpy.types.Operator):
	"""Sets collection instancing origin location from object coodinates"""
	bl_idname = "collection.set_offset_from_object" 						# Unique identifier for buttons and menu items.
	bl_label = "Set Offset from Object"  						# display name in the interface.
	bl_options = {'REGISTER', 'UNDO'}
	
	@classmethod
	def poll(cls, context):
		return (context.object is not None)

	def execute(self, context):
		scene = context.scene
		collection = context.collection
		collection.instance_offset = context.object.matrix_world.translation

		return {'FINISHED'} 												# Lets Blenderknow the operator finished successfully.

##############################################
## Sets collection instance offset from object
class COLLECTION_OT_SetOffset(bpy.types.Operator):
	"""Sets collection instancing origin location"""
	bl_idname = "collection.set_offset" 						# Unique identifier for buttons and menu items.
	bl_label = "Set Collection Offset"  						# display name in the interface.
	bl_options = {'REGISTER', 'UNDO'}

# Properties
		
	x : bpy.props.EnumProperty(
	name = 'X Offset',
	description = 'Set offset for X Axis from',
	items = [
		('NONE', 'Current', ''),
		('OBJECT', 'Object', ''),
		('CURSOR', 'Cursor', ''),
		('SCENE', 'Scene', ''),
		],
	default = 'OBJECT'
	)
			
	y : bpy.props.EnumProperty(
	name = 'Y Offset',
	description = 'Set offset for Y Axis from',
	items = [
		('NONE', 'Current', ''),
		('OBJECT', 'Object', ''),
		('CURSOR', 'Cursor', ''),
		('SCENE', 'Scene', ''),
		],
	default = 'OBJECT'
	)   	
	z : bpy.props.EnumProperty(
	name = 'Z Offset',
	description = 'Set offset for Z Axis from',
	items = [
		('NONE', 'Current', ''),
		('OBJECT', 'Object', ''),
		('CURSOR', 'Cursor', ''),
		('SCENE', 'Scene', ''),
		],
	default = 'OBJECT'
	)

	parents : bpy.props.BoolProperty(
		name='Parent Objects Only',
		description='Set offset only from parent objects',
		default = False
		)
		
	offsetX : FloatProperty(
		name='Offset X',
		description='Additional increment for collection instance X axis offset',
		subtype='DISTANCE',
		min=-100000.0, max=100000.0,
		default=0.0,
		)
	offsetY : FloatProperty(
		name='Offset Y',
		description='Additional increment for collection instance Y axis offset',
		subtype='DISTANCE',
		min=-100000.0, max=100000.0,
		default=0.0,
		)
	offsetZ : FloatProperty(
		name='Offset Z',
		description='Additional increment for collection instance Z axis offset',
		subtype='DISTANCE',
		min=-100000.0, max=100000.0,
		default=0.0,
		)
			
	def execute(self, context):
		if self.parents == False:
			sel = bpy.context.selected_objects
		else:
			sel = [obj for obj in bpy.context.selected_objects if obj.parent == None]
			
		for obj in sel:
			collections = obj.users_collection
			for col in collections:
				if self.x == 'OBJECT':
					col.instance_offset.x = obj.matrix_world.translation.x + self.offsetX
				elif self.x == 'CURSOR':
					col.instance_offset.x = bpy.context.scene.cursor.location.x + self.offsetX
				elif self.x == 'SCENE':
					col.instance_offset.x = 0
				
				if self.y == 'OBJECT':
					col.instance_offset.y = obj.matrix_world.translation.y + self.offsetY
				elif self.y == 'CURSOR':
					col.instance_offset.y = bpy.context.scene.cursor.location.y + self.offsetY
				elif self.y == 'SCENE':
					col.instance_offset.y = 0

				if self.z == 'OBJECT':
					col.instance_offset.z = obj.matrix_world.translation.z + self.offsetZ
				elif self.z == 'CURSOR':
					col.instance_offset.z = bpy.context.scene.cursor.location.z + self.offsetZ
				elif self.z == 'SCENE':
					col.instance_offset.z = 0
			
		return {'FINISHED'} 											# Lets Blenderknow the operator finished successfully.

	def draw (self, context):
		layout = self.layout
		row=layout.row()
		row.label(text="From")
		row.prop(self, 'parents')
		row=layout.row()
		row.label(text="X")
		row.prop(self, 'x', expand=True)
		row=layout.row()
		row.label(text="Y")
		row.prop(self, 'y', expand=True)
		row=layout.row()
		row.label(text="Z")
		row.prop(self, 'z', expand=True)
		col=layout.column(align=True)
		col.prop(self, 'offsetX')
		col.prop(self, 'offsetY')
		col.prop(self, 'offsetZ')

##################
## Transfer Names
class OBJECT_OT_TransferNames(bpy.types.Operator):
	"""Transfers names between datablocks"""
	bl_idname = "object.transfer_names" 							# Unique identifier for buttons and menu items.
	bl_label = "Transfer Names"
	bl_options = {'REGISTER', 'UNDO'}

# Properties
		
	source : bpy.props.EnumProperty(
	name = 'Source',
	description = 'Copy name from',
	items = [
		('NONE', 'None', "Don't copy"),
		('OBJECT', 'Object', 'Object name'),
		('DATA', 'ObjectData', 'Name from object data'),
		('TEXT', 'Text', 'Text ObjectData string'),
		('MATERIAL', 'Material', 'Name from active material'),
		('COLLECTION', 'Collection', 'Parent Collection'),
		('INSTANCE', 'Collection Instance', 'Collection Instance Name'),
		('PARENT', 'Parent', 'Parent Object'),		
		],
	default = 'OBJECT'
	)
	
	concatenation : bpy.props.EnumProperty(
	name = 'Concatenation',
	description = 'Concatenation Mode',
	items = [
		('REPLACE', 'Replace', "Replace current name"),
		('PREPEND', 'Prefix', 'Add as prefix to the beginning of current name'),
		('APPEND', 'Suffix', 'Add as suffix to the end current name'),
		],
	default = 'REPLACE'
	)
	
	source_material_index : bpy.props.IntProperty(
		name = 'Source Material Index',
		description = 'Material slot index to copy name from, 0 for Active Slot material',
		min = 0,
		default = 0
		)
	
	source_collection_index : bpy.props.IntProperty(
		name = 'Source Collection Index',
		description = 'Collection index to copy name from, if object is in more than one (Sorted Alphabetically)',
		min = 1,
		default = 1
		)
	
	target_object : bpy.props.BoolProperty(
		name='Target Object Name',
		description='Copy name to object',
		default = True
		)

	target_data : bpy.props.BoolProperty(
		name='Target Object Data Name',
		description='Copy name to object data',
		default = True
		)
				
	target_collection : bpy.props.BoolProperty(
		name='Target Collection Name',
		description='Copy name to collection',
		default = False
		)

	target_collection_index : bpy.props.IntProperty(
		name = 'Target Collection Index',
		description = 'Collection index to copy name to, if object is in more than one (Sorted Alphabetically)',
		min = 1,
		default = 1
		)

	prefix : bpy.props.StringProperty(
		name = "Prefix",
		description = 'Custom prefix for new names',
		default = "")
		
	suffix : bpy.props.StringProperty(
		name = "Suffix",
		description = 'Custom suffix for new names',
		default = "")
	
	strip : bpy.props.BoolProperty(
		name = 'Strip Numbers',
		description = 'Remove trailing numbers like ".012"',
		default = False
		)
			
# Functions
	
	def transfernames(self, context):
		
		for obj in bpy.context.selected_objects:
			
			# Sourcing Base Name
			if self.source == 'NONE':
				source = ""
			elif self.source == 'OBJECT':
				source = obj.name
			elif self.source == 'DATA' and obj.data != None:
				source = obj.data.name
				
			elif self.source == 'MATERIAL':
				if len(obj.material_slots) == 0:
					continue
				elif self.source_material_index == 0 and obj.active_material != None:
					source = obj.active_material.name
				elif self.source_material_index <= len(obj.material_slots) - 1 and obj.material_slots[self.source_material_index -1] != None:
					source = obj.material_slots[self.source_material_index - 1].name
				else:
					source = obj.material_slots[len(obj.material_slots) - 1].name

			elif self.source == 'COLLECTION':
				sortedcol = sorted(obj.users_collection, key = lambda o: o.name)
				if self.source_collection_index <= len(obj.users_collection)- 1:
					source = sortedcol[self.source_collection_index - 1].name
				elif sortedcol[self.source_collection_index - 1]:
					source = sortedcol[len(obj.users_collection) - 1].name
				else:
					continue
					
			elif self.source == 'INSTANCE' and obj.instance_collection != None:
				source = obj.instance_collection.name
			elif self.source == 'PARENT' and obj.parent != None:
				source = obj.parent.name
			elif self.source == 'TEXT' and obj.type == 'FONT':
				source = obj.data.body
			else:
				continue
			
			# Strip Numbering
			if self.strip == True and self.source != 'TEXT':
				source = source.rsplit(".", 1)[0]
			
			# Renaming Objects
			if self.concatenation == 'REPLACE':
				if self.target_object == True:
					obj.name = self.prefix + source + self.suffix
				if self.target_data == True and obj.data != None:
					obj.data.name = self.prefix + source + self.suffix
				if self.target_collection == True:
					sortedcol = sorted(obj.users_collection, key = lambda o: o.name)
					if self.target_collection_index <= len(obj.users_collection) -1 and sortedcol[self.source_collection_index - 1] is not bpy.context.scene.collection:
						sortedcol[self.source_collection_index - 1].name = self.prefix + source + self.suffix
					elif sortedcol[self.source_collection_index - 1] is not bpy.context.scene.collection:
						sortedcol[self.source_collection_index - 1].name = self.prefix + source + self.suffix
					else:
						continue
			
			elif self.concatenation == 'PREPEND':
				if self.target_object == True:
					obj.name = self.prefix + source + self.suffix + " " + obj.name
				if self.target_data == True and obj.data != None:
					obj.data.name = self.prefix + source + self.suffix + " " + obj.data.name
				if self.target_collection == True:
					sortedcol = sorted(obj.users_collection, key = lambda o: o.name)
					if self.target_collection_index <= len(obj.users_collection) -1 and sortedcol[self.source_collection_index - 1] is not bpy.context.scene.collection:
						sortedcol[self.source_collection_index - 1].name = self.prefix + source + self.suffix + " " + sortedcol[self.source_collection_index - 1].name
					elif sortedcol[self.source_collection_index - 1] is not bpy.context.scene.collection:
						sortedcol[self.source_collection_index - 1].name = self.prefix + source + self.suffix + " " + sortedcol[self.source_collection_index - 1].name
					else:
						continue

			elif self.concatenation == 'APPEND':
				if self.target_object == True:
					obj.name =  obj.name + " " + self.prefix + source + self.suffix
				if self.target_data == True and obj.data != None:
					obj.data.name = obj.data.name + " " + self.prefix + source + self.suffix
				if self.target_collection == True:
					sortedcol = sorted(obj.users_collection, key = lambda o: o.name)
					if self.target_collection_index <= len(obj.users_collection) -1 and sortedcol[self.source_collection_index - 1] is not bpy.context.scene.collection:
						sortedcol[self.source_collection_index - 1].name = sortedcol[self.source_collection_index - 1].name + " " + self.prefix + source + self.suffix
					elif sortedcol[self.source_collection_index - 1] is not bpy.context.scene.collection:
						sortedcol[self.source_collection_index - 1].name = sortedcol[self.source_collection_index - 1].name + " " + self.prefix + source + self.suffix
					else:
						continue
				
	def draw (self, context):
		layout = self.layout
		layout.use_property_split = True
		layout.label(text="Source",)
		layout.prop(self, 'source', text ="Copy From")
		layout.prop(self, 'strip')
		if self.source == 'COLLECTION':
			layout.prop(self, 'source_collection_index', text="Collection Index")
		elif self.source == 'MATERIAL':
			layout.prop(self, 'source_material_index', text="Material Index")
		else:
			layout.label(text="")
		layout.label(text="Target")
		row=layout.row(align=True)
		row.prop(self, 'target_object', text="Object")
		row.prop(self, 'target_data', text="Data")
		row=layout.row(align=True)
		row.prop(self, 'target_collection', text="Collection")
		row=layout.row(align=True)
		row.prop(self, 'target_collection_index', text="Collection Index")
		layout.prop(self, 'concatenation')
		layout.prop(self, 'prefix', text="Prefix")
		layout.prop(self, 'suffix', text="Suffix")
				
	def execute(self, context):
		self.transfernames(self)
		return {'FINISHED'} 											# Lets Blenderknow the operator finished successfully.

	
###########################
## Create Collections From Objects
class COLLECTION_OT_CreateFromObject(bpy.types.Operator):
	"""Creates new collections for each selected object and automatically sets its offset"""
	bl_idname = "object.collectioncreate"
	bl_label = "Create Collections From Objects"
	bl_options = {'REGISTER', 'UNDO'}

# Properties

	prefix : bpy.props.StringProperty(
		name = "Prefix",
		description = 'Prefix for new collection names',
		default = "")
		
	suffix : bpy.props.StringProperty(
		name = "Suffix",
		description = 'Suffix for new collection names',
		default = "")
		
	mode : bpy.props.EnumProperty(
		name = 'Hierarchy Mode',
		description = 'Move or link objects to the new collections',
		items = [
			('MOVE', 'Move', ''),
			('LINK', 'Link', ''),
			],
		default = 'MOVE'
		)

	child : bpy.props.EnumProperty(
		name = 'Children Hierarchy',
		description = 'Also move or link child objects to the new collections',
		items = [
			('MOVE', 'Move', ''),
			('LINK', 'Link', ''),
			('CURRENT', 'Current', ''),
			],
		default = 'LINK'
		)
		
	root : bpy.props.EnumProperty(
		name = 'Root',
		description = 'Root collection for creating new collections',
		items = [
			('ACTIVE', 'Active Collection', ''),
			('SCENE_COLLECTION', 'Scene Collection', ''),
			],
		default = 'ACTIVE'
		)

	strip : bpy.props.BoolProperty(
		name = 'Strip Numbers',
		description = 'Remove trailing numbers like ".01a2"',
		default = False
		)

	parents : bpy.props.BoolProperty(
		name='Parent Objects Only',
		description='Create collections only from top level parent objects',
		default = False
		)
# Functions
				
	def createcollections (self, context):
		scene = bpy.context.scene.collection
		if self.parents == False:
			sel = bpy.context.selected_objects
		else:
			sel = [obj for obj in bpy.context.selected_objects if obj.parent == None]
				
		def getchildren (parent):
			for child in parent.children:
				yield child
				yield from getchildren(child)
				
		#Set parent collection for instance creation
		if self.root == 'ACTIVE':
			rootcol = bpy.context.view_layer.active_layer_collection.collection
		elif self.root == 'SCENE_COLLECTION':
			rootcol = bpy.context.scene.collection
		
		for obj in sel:
			if self.strip == True:
				name = obj.name.rsplit(".", 1)[0]
			else:
				name = obj.name
				
			loc = obj.matrix_world.translation
			
			#Create Collections
			col = bpy.data.collections.new(self.prefix + name + self.suffix)
			#Link to parent collection
			rootcol.children.link(col)
			# Set Instance offset coordinates
			bpy.data.collections[col.name].instance_offset = loc
			
			if self.mode == 'MOVE':
				for cols in obj.users_collection:
					cols.objects.unlink(obj)
			
			if self.child == 'MOVE':
				for child in getchildren(obj):
					for cols in child.users_collection:
						cols.objects.unlink(child)
					bpy.data.collections[col.name].objects.link(child)
			
			elif self.child == 'LINK':
				for child in getchildren(obj):
					bpy.data.collections[col.name].objects.link(child)
			
			# Link objects to new collections
			bpy.data.collections[col.name].objects.link(obj)
			
	def draw (self, context):
		layout = self.layout
		layout.use_property_split = True
		layout.prop(self, 'mode', text="Mode")
		layout.prop(self, 'child', text="Child")
		layout.prop(self, 'root' , text="Root")
		row=layout.row(align=True)
		row.prop(self, 'strip' , text="Strip")
		row.prop(self, 'parents' , text="Parents")
		layout.prop(self, 'prefix')
		layout.prop(self, 'suffix')
		
	def execute(self, context):
		self.createcollections(self)
		return {'FINISHED'}

###########################
## Duplicate Collections Hierarchy

class COLLECTION_OT_CollectionDuplicateHierarchy(bpy.types.Operator):
	"""Duplicates the current collection hierarchy linking objects without creating new ones"""
	bl_idname = "outliner.collectionduplicatehierarchy"
	bl_label = "Duplicate Collection Hierarchy"
	bl_options = {'REGISTER', 'UNDO'}
	
	def duplicate_hierarchy(self, context):
		scene = bpy.context.scene
		collection = bpy.context.collection
		scene_collections = [
			col for col in bpy.data.collections 
			if scene.user_of_id(col)
			]
		scene_collections.append(bpy.context.scene.collection)
		root = [col for col in scene_collections
			if col.user_of_id(collection)]
		
		def collection_duplicator(collection, parent):
			duplicate = bpy.data.collections.new(collection.name)
			parent.children.link(duplicate)
			
			for obj in collection.objects:
				bpy.data.collections[duplicate.name].objects.link(obj)
			for col in collection.children:
				collection_duplicator(col, duplicate)
			
		collection_duplicator(collection, root[0])
		
	def execute(self, context):
		self.duplicate_hierarchy(self)
		return {'FINISHED'}

#bpy.ops.script.reload()

#############################################################################################
# Menus

### 3D View Header Menu > Object > Collection

def View3D_MT_CollectionUtilities(self, context):
	layout = self.layout
	layout.separator()
	layout.operator("collection.set_offset")
	layout.operator("object.collectioncreate")

### 3D View Header Menu > Object > Make Links

def View3D_MT_transfer_names(self, context):
	layout = self.layout
	layout.operator("object.transfer_names")

### Properties Window > Object > Collections > Collection Context Menu

def PROPERTIES_MT_collection_menu(self, context):
	layout = self.layout
	layout.operator("collection.set_offset_from_object")

### Outliner Collection Context Menu > Duplicate Hierarchy

def OUTLINER_MT_DuplicateHierarchy(self, context):
	layout = self.layout
	layout.operator("outliner.collectionduplicatehierarchy")

classes = (
	COLLECTION_OT_CreateFromObject,
	COLLECTION_OT_SetOffset,
	COLLECTION_OT_OffsetFromObject,
	COLLECTION_OT_CollectionDuplicateHierarchy,
	OBJECT_OT_TransferNames,
	)
		
def register():
	for cla in classes:
		bpy.utils.register_class(cla)
	bpy.types.VIEW3D_MT_object_collection.append(View3D_MT_CollectionUtilities)
	bpy.types.COLLECTION_MT_context_menu.append(PROPERTIES_MT_collection_menu)
	bpy.types.VIEW3D_MT_make_links.append(View3D_MT_transfer_names)
	bpy.types.OUTLINER_MT_collection.append(OUTLINER_MT_DuplicateHierarchy)

def unregister():
	for cla in classes:
		bpy.utils.unregister_class(cla)
	bpy.types.VIEW3D_MT_object_collection.remove(View3D_MT_CollectionUtilities)
	bpy.types.COLLECTION_MT_context_menu.remove(PROPERTIES_MT_collection_menu,)
	bpy.types.VIEW3D_MT_make_links.remove(View3D_MT_transfer_names)
	bpy.types.OUTLINER_MT_collection.remove(OUTLINER_MT_DuplicateHierarchy)

if __name__ == "__main__":
	register()
