extends Control

onready var map_menu = $menu/menubar/MapMenu.get_popup()
onready var map_node = $map

const MAP_SCALE_MAX = 8
const MAP_SCALE_MIN = 0.25

func _ready():
	pass

# Prevent input handler from running when other dialogs/actions are focused
var input_lock = false

# Drag variables
var dragging = false
var view_origin = Vector2.ZERO
var mouse_origin = Vector2.ZERO

func _input(ev: InputEvent):
	if input_lock:
		return
	
	if ev is InputEventMouseMotion:
		if dragging:
			map_node.position = view_origin - (mouse_origin - ev.global_position)
		else:
			# Map cursor location to grid
			var mouse_offset = ev.global_position - map_node.global_position
			
	
	if ev is InputEventMouseButton:
		var mouse = ev as InputEventMouseButton
		if mouse.pressed:
			match ev.button_index:
				BUTTON_WHEEL_UP:
					# Zoom in
					if map_node.scale.x < MAP_SCALE_MAX:
						if map_node.scale.x < 1:
							map_node.scale *= 2
						else:
							map_node.scale += Vector2.ONE
				BUTTON_WHEEL_DOWN:
					# Zoom out
					if map_node.scale.x > MAP_SCALE_MIN:
						if map_node.scale.x <= 1:
							map_node.scale /= 2
						else:
							map_node.scale -= Vector2.ONE
				BUTTON_MIDDLE:
					view_origin = map_node.position
					mouse_origin = ev.global_position
					dragging = true
		else:
			match ev.button_index:
				BUTTON_MIDDLE:
					dragging = false
					map_node.position = view_origin - (mouse_origin - ev.global_position)
