extends TileMap

class_name Board

var tile_by_name := {}
var layer_by_name := {}
var tile_map_layer = 1

@export var state_layer: String = "States"
@export var board_layer: String = "Board"
@export var state_name: String = "Name"
@export var empty_state: String = "Empty"
var off_limits: String = ""
@export var active: bool = true


func _ready():
	print("Initializing board...")
	_index_atlas_coordinates_by_name()
	_index_layers_by_name()
	$Highlight.size = tile_set.tile_size
	print("Tiles: ", ", ".join(tile_by_name.keys()))


func get_state(grid_pos: Vector2) -> String:
	var state_tile_data: TileData = self.get_cell_tile_data(layer_by_name[state_layer], grid_pos)
	var board_tile_data: TileData = self.get_cell_tile_data(layer_by_name[board_layer], grid_pos)
	if not board_tile_data:
		return off_limits
	if not state_tile_data or not state_tile_data.get_custom_data(state_name):
		return empty_state
	return state_tile_data.get_custom_data(state_name)

func set_state(grid_pos: Vector2, state: String) -> bool:
	if get_state(grid_pos) != empty_state:
		return false
	self.set_cell(layer_by_name[state_layer], grid_pos, tile_by_name[state]["source_id"], tile_by_name[state]["atlas_coords"])
	return true

func global_to_map(global_pos: Vector2) -> Vector2:
	return self.local_to_map(self.to_local(global_pos))

func gridpos_at_mouse() -> Vector2:
	return global_to_map(get_viewport().get_mouse_position()) 

func reset() -> void:
	for cell in get_used_cells(layer_by_name[state_layer]):
		set_cell(layer_by_name[state_layer], cell, -1)

func _index_atlas_coordinates_by_name():
	var tileset = self.tile_set
	for source_index in range(tileset.get_source_count()):
		var source_id = tileset.get_source_id(source_index)
		var atlas:TileSetAtlasSource = tileset.get_source(source_id)
		for tile_index in range(atlas.get_tiles_count()):
			var atlas_coords = atlas.get_tile_id(tile_index)
			var tile_data : TileData = atlas.get_tile_data(atlas_coords, 0)
			if tile_data and tile_data.get_custom_data(state_name):
				tile_by_name[tile_data.get_custom_data(state_name)] = {
					"source_id": source_id,
					"atlas_coords": atlas_coords
				}
	
func _index_layers_by_name():
	for i in range(get_layers_count()):
		layer_by_name[get_layer_name(i)] = i
		
func _calculate_drop_pos(grid_pos: Vector2) -> Vector2:
	var x_coord = floor(grid_pos.x)  # Round down to get the grid cell
	var y_coord

	# Check each row from bottom to top for an empty space
	for i in range(6, -1, -1):  # Iterate from bottom to top
		if self.get_state(Vector2(x_coord, i)) == self.empty_state:
			y_coord = i
			break  # Exit the loop once an empty space is found
		else: i = i - 1

	return Vector2(x_coord, y_coord)

#Löscht eine Zeile nach dem Glücksrad ereignis 
func delete_column(column: int) -> void:
	for j in range((column - 2), -1, -1):
		for i in range(-2, 4, 1): 
			var tile_map_cell_position = Vector2i(i,j) 
			var tile_data = self.get_cell_tile_data(tile_map_layer, tile_map_cell_position)
			if tile_data: 
				var tile_map_cell_source_id = self.get_cell_source_id(tile_map_layer, tile_map_cell_position); 
				var tile_map_cell_atlas_coords = self.get_cell_atlas_coords(tile_map_layer, tile_map_cell_position) 
				var tile_map_cell_alternative = self.get_cell_alternative_tile(tile_map_layer, tile_map_cell_position)
				print(tile_map_cell_source_id)
				print(tile_map_cell_atlas_coords)
				print(tile_map_cell_alternative)  
				var new_tile_map_cell_position = Vector2i(i, j + 1)
				self.set_cell(tile_map_layer, new_tile_map_cell_position, tile_map_cell_source_id, tile_map_cell_atlas_coords, tile_map_cell_alternative)
				if j == 0:
					self.set_cell(tile_map_layer, Vector2i(i, 0))
			else:
				#Falls kein Inhalt, leer setzten
				self.set_cell(tile_map_layer, Vector2i(i, j + 1))
					
func delete_row(row: int) -> void:
	for i in range(6):
		#Inhalt leer setzten (row -3 damit es mit 1 - 6 funktioniert)
		self.set_cell(tile_map_layer, Vector2i(row - 3, i))
		
		
func _clear_enemy_tile(grid_pos: Vector2) -> void:
	var true_position = grid_pos
	self.set_cell(tile_map_layer, true_position)
	for i in range(true_position.y - 1, -1, -1 ):
		var tile_map_cell_position = Vector2i(true_position.x, i) 
		var tile_data = self.get_cell_tile_data(tile_map_layer, tile_map_cell_position)
		if tile_data: 
			var tile_map_cell_source_id = self.get_cell_source_id(tile_map_layer, tile_map_cell_position); 
			var tile_map_cell_atlas_coords = self.get_cell_atlas_coords(tile_map_layer, tile_map_cell_position) 
			var tile_map_cell_alternative = self.get_cell_alternative_tile(tile_map_layer, tile_map_cell_position)  
			var new_tile_map_cell_position = Vector2i(true_position.x, i + 1)
			self.set_cell(tile_map_layer, new_tile_map_cell_position, tile_map_cell_source_id, tile_map_cell_atlas_coords, tile_map_cell_alternative)
			if i == 0:
				self.set_cell(tile_map_layer, Vector2i(true_position.x, 0))
		else:
			#Falls kein Inhalt, leer setzten
			self.set_cell(tile_map_layer, Vector2i(true_position.x, i + 1))
