extends Node2D

@onready var CURSOR = $Cursor
var is_drawing : bool = false

func _ready() -> void:
	for x in range(64, get_viewport_rect().size.x, 96):
		for y in range(64, get_viewport_rect().size.y, 96):
			var c = Globals.SCENE_COLLECTABLE.instantiate()
			c.global_position = Vector2(x, y)
			c.type = randi() % 2
			add_child(c)
	$Camera2D.position = get_viewport_rect().size / 2

#func _draw() -> void:
	#var trail = CURSOR.get_tail(Globals.HISTORY_LENGTH)
	#
	#if trail.size() <= 0:
		#return
	#
	#for i in range(trail.size() - 1):
		#var color
		#if trail.size() > Globals.HISTORY_LENGTH * .66:
			#color = Color(.5,0,0,1)
		#elif trail.size() > Globals.HISTORY_LENGTH * .33:
			#color = Color(.5,.5,0,1)
		#else:
			#color = Color(0,.5,0,1)
		#draw_line(trail[i], trail[i + 1], color , Globals.LINE_THICC, false)

func _process(delta: float) -> void:
	if is_drawing:
		var trail = CURSOR.get_tail(Globals.HISTORY_LENGTH)
		$LineProgress/InkWell.points = PackedVector2Array(trail)
	
	while CURSOR.loop_stack.size() > 0:
		var loop = CURSOR.loop_stack.pop_back()
		create_loop_object(loop)

func create_loop_object(loop:Array):
	var scene = Globals.SCENE_LOOP.instantiate()
	scene.points = loop
	if Geometry2D.decompose_polygon_in_convex(PackedVector2Array(loop)).size() == 0:
		scene.is_error = true
	add_child(scene)
	await get_tree().create_timer(.2).timeout
	var contents = scene.get_contained_nodes()
	process_collection(contents)

func process_collection(contents:Array) -> void:
	var collectables = get_tree().get_nodes_in_group("collectable")
	var type : int = -1
	var count : int = 0
	var mistakes : int = 0
	
	for i in range(len(contents)):
		var obj = contents[i]
		
		if not (obj in collectables):
			continue
		
		if type == -1 or obj.type == type:
			type = obj.type
			count += 1
		else:
			obj.is_good = false
			mistakes += 1
		
		obj.remove(i)
	
	print("Good: " + str(count) + "; Bad: " + str(mistakes))

func _on_cursor_started_drawing(pos:Vector2) -> void:
	print("started drawing")
	var cam = get_viewport().get_camera_2d()
	var t = get_tree().create_tween()
	t.tween_property(Engine, "time_scale", 0.2, .2)
	$StartMarker.global_position = pos
	$StartMarker.visible = true
	$LineProgress.visible = true
	is_drawing = true
	$AudioSlowDownStart.play()
	await $AudioSlowDownStart.finished
	$AudioSlowDownLoop.play()

func _on_cursor_stopped_drawing(data:Array) -> void:
	print("stopped drawing")
	var cam = get_viewport().get_camera_2d()
	var t = get_tree().create_tween()
	t.tween_property(Engine, "time_scale", 1.0, .2)
	$StartMarker.visible = false
	$LineProgress.visible = false
	is_drawing = false
	if CURSOR.loop_stack.size() == 0:
		var err_loop = Globals.SCENE_LOOP.instantiate()
		err_loop.is_error = true
		err_loop.points = data
		add_child(err_loop)
	$AudioSlowDownStart.stop()
	$AudioSlowDownLoop.stop()
	$AudioSlowDownEnd.play()
