import bpy
import time
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


class RoadPortionNodeAddDatablockSocketOperator(bpy.types.Operator):
	bl_idname = 'node.road_portion_node_add_datablock_socket'
	bl_label = 'Add datablock'
	bl_description = 'Add a datablock to this road portion, such as a mesh or object group'
	source_node_path = bpy.props.StringProperty()

	def execute(self, context):
		source_node = eval(self.source_node_path)
		random_string = time.time()
		source_node.inputs.new('OptionalDatablockSocket', str(random_string))
		return {'FINISHED'}


class RoadPortionNode(Node, CityNodeTreeNode):
	bl_label = 'Road portion'

	road_portion_type = bpy.props.EnumProperty(
		name='Type',
		description='Roads are made of portions put together.',
		items=[
			('STRAIGHT', 'Straight along X', '', 1),
			('TURN', 'Turn from -Y to +X', '', 2),
			('DEAD_END', 'Dead end, stop at -X', '', 3),
			('INTERSECTION_3', 'Intersect 3, along Y and to +X', '', 4),
			('INTERSECTION_4', 'Intersect 4, along X and Y', '', 5),
		])

	width_grid = bpy.props.IntProperty(
		name='Width',
		description='Width of the road, in city grid cells',
		default=1)

	length_grid = bpy.props.IntProperty(
		name='Length',
		description='Length of the road, in city grid cells',
		default=1)

	user_data = 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_building = bpy.props.StringProperty()

	def init(self, context):
		self.width = 300
		self.outputs.new('CityAssetSocket', 'Road portion')

	def draw_buttons(self, context, layout):
		row = layout.row()
		row.prop(self, 'road_portion_type')
		row = layout.row()
		row.prop(self, 'width_grid')
		if self.road_portion_type == 'STRAIGHT' or self.road_portion_type == 'DEAD_END':
			row = layout.row()
			row.prop(self, 'length_grid')
		row = layout.row()
		row.prop(self, 'user_data')
		op = layout.operator('node.road_portion_node_add_datablock_socket')
		op.source_node_path = 'bpy.data.node_groups["' + self.id_data.name + '"].' + self.path_from_id()

	def update(self):
		pass
