extends Node2D

#Noise

@export var noiseTexture : NoiseTexture2D
var noise : Noise

# Export groups

@export_group("Noise settings")
@export var width = 1000
@export var height = 1000

# Tilemap
@onready var tileMapLayer = %TileMapLayer
@onready var buildables_layer: TileMapLayer = $BuildablesLayer
var source_id = 0
var low_grass_id = Vector2(0,0)
var high_grass_id = Vector2(1,0)
var shallow_water_id = Vector2(2,0)
var water_id = Vector2(3,0)
var sand_id = Vector2(4,0)
var mountain_id = Vector2(5,0)
var snow_id = Vector2(6,0)


# Misc
@onready var player: CharacterBody2D = %Player
const ZOMBIE = preload("uid://b6l0phnbjeims")
const DROWNED = preload("uid://yuuwv117hgel")

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	noiseTexture.noise.seed = randi()
	noise = noiseTexture.noise
	_generate_world()


func _generate_world():
	for x in range(-width / 2, width / 2):
		for y in range(-height / 2, height / 2):
			var noise_value = noise.get_noise_2d(x, y) # get value of noise map
			if noise_value <= -0.4: # Water
				tileMapLayer.set_cell(Vector2i(x,y), source_id, water_id)
			elif noise_value <= -0.3: # shallow water
				tileMapLayer.set_cell(Vector2i(x,y), source_id, shallow_water_id)
			elif noise_value <= -0.2: # sand
				tileMapLayer.set_cell(Vector2i(x,y), source_id, sand_id)
			elif noise_value <= 0.2: # low grass
				tileMapLayer.set_cell(Vector2i(x,y), source_id, low_grass_id)
				if randf() < 0.0075:
					buildables_layer.set_cell(Vector2i(x,y), source_id, Vector2i(0,0)) # Bush
			elif noise_value <= 0.35: # high grass
				tileMapLayer.set_cell(Vector2i(x,y), source_id, high_grass_id)
			elif noise_value <= 0.5: # mountain
				tileMapLayer.set_cell(Vector2i(x,y), source_id, mountain_id)
			else: # snow
				tileMapLayer.set_cell(Vector2i(x,y), source_id, snow_id)
	_find_good_spawn()

func _find_good_spawn():
	for x in range(-width / 4, width / 4):
		for y in range(-height / 4, height / 4):
			for z in range(-4, 5):
				var noise_value = noise.get_noise_2d(x + z, y + z)
				if noise_value > 0.2 and noise_value <= 0.35:
					player.global_position = tileMapLayer.map_to_local(Vector2i(x + z,y + z))
					if z == 4:
						return


func _on_mob_spawn_timeout() -> void:
	var pos = player.global_position + Vector2(randf_range(-200, 200), 200)
	var tile_pos = tileMapLayer.local_to_map(pos)
	var tile_data = tileMapLayer.get_cell_atlas_coords(tile_pos)
	var new_zombie
	if tile_data == Vector2i(3,0):
		new_zombie = DROWNED.instantiate()
	else:
		new_zombie = ZOMBIE.instantiate()
	new_zombie.global_position = pos
	add_child(new_zombie)
