import bpy
import random
import math
import pickle
# from .general import DirectionalPoint2d, Rect2d, DirectionalPoints2dCollection
# from ..utils import définirPixel
from bpy.types import Node
from .. import CityNodeTreeNode, Taggable


class Datablock(Taggable):
	def __init__(self):
		Taggable.__init__()
		self.type = None  # MESH, GROUP, etc...
		self.name = None

	def get_data(self, **kwargs):
		try:
			if self.type == 'MESH':
				return bpy.data.meshes[self.name]
			elif self.type == 'GROUP':
				return bpy.data.groups[self.name]
		except:
			return None


class DatablockNode(Node, CityNodeTreeNode):
	bl_label = 'Blender datablock'
	datablock_type = bpy.props.EnumProperty(
		name='Type',
		description='',
		items=[
			('MESH', 'DATA_Mesh', '', 1),
			('GROUP', 'Object group', '', 2),
		])
	datablock_name = bpy.props.StringProperty(
		name='Datablock name',
		description='Name of the mesh or object group', )
	tags = bpy.props.StringProperty(
		name='Tags',
		description='Set your custom data here. They act like tags, and can be used by various algorithms further down in the graph hierarchy. Check the doc '
					'for more information.', )
	pickled_datablock = bpy.props.StringProperty()

	def init(self, context):
		self.width = 300
		self.outputs.new('DatablockSocket', 'Datablock')

	def draw_buttons(self, context, layout):
		row = layout.row()
		row.prop(self, 'datablock_type')
		row = layout.row()
		icon = 'OUTLINER_DATA_MESH'
		if self.datablock_type == 'GROUP':
			icon = 'GROUP'
		row.prop(self, 'datablock_name', icon=icon)
		row = layout.row()
		row.prop(self, 'tags')

	def update(self):
		datablock = Datablock()
		datablock.type = self.datablock_type
		datablock.name = self.datablock_name
		datablock.tags_string = self.tags
		# ne pas évaluer le user data maintenant, à cause du random.seed qui pourra être ainsi défini plus tard si besoin
		self.pickled_datablock = str(pickle.dumps(datablock))
