extends TileMap

@export var playerPos :Vector2 = Vector2.ZERO

@onready var player :CharacterBody2D =$"../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 :int = rng.randi_range(0, 200)
	var randomHouse :int = rng.randi_range(5,10)
	var randomPower :int = rng.randi_range(2,8)
	var randomGap :int = rng.randi_range(1,15)
	var randomSet :Array = [rum, randomHouse,randomPower,randomGap]
	return randomSet

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

#removes old tiles
func garbageCollect(playerPost :Vector2):
	for dist in get_used_cells(0):
		if playerPost.x-dist.x > 100:
			erase_cell(0, dist)
	for dist in get_used_cells(1):
		if playerPost.x-dist.x > 100:
			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()
