extends Control

export var cell_size = 100
export var bgzoom = 50

export(Texture) var background
export(Font) var font

var dragging = false
var origin = Vector2(randf() * -1e4, randf() * -1e4)
var last_origin = origin
var last_mouse_pos = Vector2.ZERO

func _draw():
	var win_size = get_global_rect().size
	var cols = int(ceil(win_size.x/cell_size))
	var rows = int(ceil(win_size.y/cell_size))
	var xoffset = float(int(origin.x) % cell_size)
	var yoffset = float(int(origin.y) % cell_size)
	draw_texture_rect_region(background, Rect2(Vector2.ZERO, win_size), Rect2(-origin*bgzoom, win_size*bgzoom), Color(0.5,0.5,0.5,1))
	for i in range(0, cols+1):
		draw_line(Vector2(i * cell_size+xoffset, 0), Vector2(i * cell_size+xoffset, win_size.y), Color.white * 0.5)
	for i in range(0, rows):
		draw_line(Vector2(0, i * cell_size+yoffset), Vector2(win_size.x, i * cell_size+yoffset), Color.white * 0.5)
	for x in range(-1, cols+1):
		for y in range(-1, rows+1):
			var real_x = x - int(origin.x/cell_size)
			var real_y = y - int(origin.y/cell_size)
			var sector_name = to_letter(real_x)
			if real_y < 0:
				sector_name += to_letter(real_y)
			else:
				sector_name += str(real_y)
			draw_string(font, Vector2(x * cell_size + 6 + xoffset, y * cell_size + 20 + yoffset), sector_name, Color(1,1,1,0.5))

func _input(event):
	if event is InputEventMouseButton:
		dragging = event.pressed
		last_origin = origin
		last_mouse_pos = event.position
		update()
	elif event is InputEventMouseMotion:
		if dragging:
			origin = last_origin + (event.position - last_mouse_pos)
			update()

func to_letter(num: int) -> String:
	#var letters = "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
	var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	if num == 0:
		return "Α"
	elif num < 0:
		letters = "αβγδεζηθικλμνξοπρστυφχψω"
	num = abs(num)
	var out = ""
	var base = letters.length()
	while num > 0:
		out += letters.substr(num % base, 1)
		num /= base
	return out
