extends Control

const Response = preload("res://scenes/util/Response.gd")

@onready var _api = get_node("/root/API")

# Called when the node enters the scene tree for the first time.
func _ready():
	Dialogic.signal_event.connect(_on_dialogic_signal)
	if _api.user_name:
		Dialogic.VAR.user = _api.user_name

	var timeline: Variant = "res://timelines/new_player_wizard.dtl"

	var dojo : Dictionary = await _api.get_dojo()
	if not dojo.is_empty():
		var user : Dictionary = await _api.get_user()
		Dialogic.VAR.dojo = dojo['name']
		if user.has("properties") and user["properties"] is Dictionary:
			var properties: Dictionary = user["properties"]
			Dialogic.VAR.bg.clan = properties.get("bg.clan", "")
			Dialogic.VAR.bg.community = properties.get("bg.community", "")
			Dialogic.VAR.bg.country = properties.get("bg.country", "")
			Dialogic.VAR.bg.username = properties.get("bg.username", "")
			timeline = "res://timelines/main.dtl"

	Dialogic.start(timeline)


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
	pass

func _on_dialogic_signal(argument:String):
	Dialogic.paused = true
	match argument:
		"create_dojo":
			create_dojo()
		"update_preferences":
			update_preferences()
		"text_input":
			get_tree().change_scene_to_file("res://scenes/Main/CreateCharacter.tscn")
	Dialogic.paused = false

func create_dojo():
	var result: Response = await _api.create_dojo(Dialogic.VAR.newdojo)
	if result.status == OK:
		print_debug("create_dojo successful: %s - %s" % [result.code, result.data])
		Dialogic.VAR.dojo = Dialogic.VAR.newdojo
	else:
		print_debug("create_dojo failed: %s - %s" % [result.code, result.data])

func update_preferences():
	var result: Response = await _api.update_user_preferences({
		"bg.clan": Dialogic.VAR.bg.clan,
		"bg.community": Dialogic.VAR.bg.community,
		"bg.country": Dialogic.VAR.bg.country,
		"bg.username": Dialogic.VAR.bg.username
	})
	if result.status == OK:
		print_debug("update_preferences was successful!")
	else:
		print_debug("update_preferences failed: %s - %s" % [result.code, result.data])
