extends Control

@export var jobs_array: Array[JobData]
@export var job_limit: int = 5
var jobs_tab_button: Button
const JOB_SCENE = preload("uid://dvfcie8hqcb0")
const PRINTER = preload("uid://33ctlyrpibs3")

func _ready() -> void:
	%Money.text = "Money: " + str(PlayerData.money) + " €"
	%Experience.value = PlayerData.xp
	%Level.text = "Level: " + str(PlayerData.level)
	jobs_tab_button = $VBoxContainer/MainArea/RightColumn/TabSwitcher/TabButtons/JobsTabButton
	
	PlayerData.xp_changed.connect(_on_xp_changed)
	PlayerData.level_changed.connect(_on_level_changed)
	PlayerData.money_changed.connect(_on_money_changed)

func generate_job():
	var job_count = %JobContainer.get_children()
	#print("Current jobs: " + str(job_count.size()))
	
	if not job_count.size() >= job_limit:
		var random_job: JobData = jobs_array.pick_random()
		var new_job = JOB_SCENE.instantiate()
		%JobContainer.add_child(new_job)
		new_job.initialize_job(random_job)
		job_count = %JobContainer.get_children()
		jobs_tab_button.text = "Jobs (" + str(job_count.size()) + "/" + str(job_limit) + ")"
		new_job.job_accepted.connect(_on_job_accepted_pressed)

# --- Experience, Level and Money update ---
func _on_xp_changed(xp):
	%Experience.value = xp
func _on_level_changed(level):
	%Level.text = "Level: " + str(level)
func _on_money_changed(money):
	%Money.text = "Money: " + str(money) + "€"

func _on_job_accepted_pressed(accepted_job):
	print("Job accepted")
	#PlayerData.give_experience.emit(accepted_job.job_data.job_experience)
	#PlayerData.give_money.emit(accepted_job.job_data.job_reward)
	PlayerData.jobs.append(accepted_job.job_data)
	print(PlayerData.jobs[0].job_name)
	
	accepted_job.queue_free()
	var job_count = %JobContainer.get_child_count() - 1
	jobs_tab_button.text = "Jobs (" + str(job_count) + "/" + str(job_limit) + ")"

func _on_job_spawner_timeout() -> void:
	generate_job()

func _on_printers_printer_purchase_requested(printer_data: PrinterData) -> void:
	#print("Signal reached UI: " + printer_data.printer_manufacturer)
	if PlayerData.try_purchase(printer_data.printer_price):
		%Money.text = "Money: " + str(PlayerData.money) + "€"
		var new_printer = PRINTER.instantiate()
		%PrinterContainer.add_child(new_printer)
		new_printer.initialize_printer(printer_data)
