extends TileMap

@export var playerPos = Vector2.ZERO

@onready var player =$"../CharacterBody2D"
var rng = RandomNumberGenerator.new()
# Called when the node enters the scene tree for the first time.
func _ready():	
	pass

#return random int
func roller():
	var rum = rng.randi_range(0, 200)
	var randomHouse = rng.randi_range(5,10)
	var randomPower = rng.randi_range(2,8)
	var randomGap = rng.randi_range(1,20)
	var randomSet = [rum, randomHouse,randomPower,randomGap]
	return randomSet

#draws the ground, houses and powerups
func drawPat(playerPos):
	var tilePos = Vector2i(playerPos.x+(36),11)
	var tileCheck = tilePos + Vector2i(1,1)
	var rum = roller()
	
	if get_cell_tile_data(0,tileCheck,false) == null:
		set_pattern(0,tilePos +Vector2i(rum[3],0),tile_set.get_pattern(1))
		if int(playerPos.x) % 3 == 0:
			if rum[0] > 180:
				set_pattern(1,tilePos-Vector2i(-8,rum[1]),tile_set.get_pattern(4))
		if int(playerPos.x) % 7 == 0:
			if rum[0] > 180:
				set_pattern(1,tilePos-Vector2i(-8,rum[2]),tile_set.get_pattern(5))

#removes old tiles
func garbageCollect(playerPos):
	for dist in get_used_cells(0):
		if playerPos.x-dist.x > 0:
			if sqrt((playerPos.x-dist.x) ** 2 + (playerPos.y - dist.y)**2) > 200:
				erase_cell(0, dist)
	for dist in get_used_cells(1):
		if playerPos.x-dist.x > 0:
			if sqrt((playerPos.x-dist.x) ** 2 + (playerPos.y - dist.y)**2) > 200:
				erase_cell(1, dist)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	playerPos = self.local_to_map(player.position)
	if playerPos.y > 15:
		NewScript.playerDeath()
		get_tree().change_scene_to_file("res://mainMenu.tscn")
	var data = get_cell_tile_data(1,playerPos)
	if data: 
		NewScript.hit(data.get_custom_data_by_layer_id(0))
	drawPat(playerPos)
	garbageCollect(playerPos)
	
	NewScript.playerPoScore()
