tool
extends SummerDayTool
class_name SummerDayZoomCanvasTool


var zoom_activated := false
var initial_transform: Transform2D
var initial_mouse_position: Vector2
var is_space_pressed = false


func _init():
	priority = 1
	modifier_layer = 1


func _handle_global_input(event: InputEvent):
	if event is InputEventKey:
		if event.scancode == KEY_SPACE:
			is_space_pressed = event.is_pressed()


func _check_for_use(event: InputEvent):
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT:
			if event.is_pressed() and is_space_pressed:
				initial_transform = SummerDay.canvas_state.canvas_transform
				initial_mouse_position = event.position
				zoom_activated = true
			else:
				zoom_activated = false
		elif event.factor != 0.0 and event.button_index >= 4:
			initial_transform = SummerDay.canvas_state.canvas_transform
			return true
	
	if event is InputEventMouseMotion:
		return zoom_activated
	
	return false


func _run(event: InputEvent):
	var zoom_point
	var zoom_strength
	
	if event is InputEventMouseButton:
		zoom_point = event.position
		zoom_strength = event.factor
		if event.button_index == BUTTON_WHEEL_DOWN:
			zoom_strength = -event.factor
	if event is InputEventMouseMotion:
		zoom_point = initial_mouse_position
		zoom_strength = (event.position.x - initial_mouse_position.x) * 0.5
	
	var canvas_transform = initial_transform
	canvas_transform.origin -= zoom_point
	var scale = pow(1.03, zoom_strength)
	canvas_transform = canvas_transform.scaled(Vector2(scale, scale))
	canvas_transform.origin += zoom_point
	SummerDay.canvas_state.canvas_transform = canvas_transform
