class_name TimeEntryTreeItem

signal end_time_updated

var time_entry: TimeEntry
var children := {}
var time_entries := []


func get_child(parts: Array, or_create := false):
	# workaround for cyclic dependencies bug
	var TimeEntryTreeItem = load("res://scripts/time_entry_tree_item.gd")
	if parts.size() == 0:
		return self
	var part: String = parts.pop_front()
	if not children.has(part):
		if or_create == false:
			return null
		var time_entry_tree_item = TimeEntryTreeItem.new()
		# warning-ignore:return_value_discarded
		time_entry_tree_item.connect("end_time_updated", self, "_on_end_time_updated")
		children[part] = time_entry_tree_item
	return children[part].get_child(parts, or_create)


func find_active_time_entry() -> TimeEntry:
	for _time_entry_tree_item in time_entries:
		var time_entry_tree_item := _time_entry_tree_item as TimeEntryTreeItem
		var current_time_entry := time_entry_tree_item.time_entry
		if not current_time_entry.is_closed:
			return current_time_entry
	return null


func append(new_time_entry: TimeEntry) -> void:
	var TimeEntryTreeItem = load("res://scripts/time_entry_tree_item.gd")
	var time_entry_tree_item = TimeEntryTreeItem.new()
	time_entry_tree_item.time_entry = new_time_entry
	time_entries.append(time_entry_tree_item)


func _on_end_time_updated() -> void:
	emit_signal("end_time_updated")


func get_elapsed_seconds() -> int:
	var seconds := time_entry.get_elapsed_seconds() if time_entry != null else 0
	for child_name in children:
		var child = children[child_name]
		seconds += child.get_elapsed_seconds()
	for entry in time_entries:
		seconds += entry.get_elapsed_seconds()
	return seconds


func get_period() -> String:
	var time_in_secs := get_elapsed_seconds()
	return TimeEntry.time_to_period(time_in_secs)


func to_dict() -> Dictionary:
	var json := {}
	var times := []
	if time_entries.size() > 0:
		for entry in time_entries:
			times.append(entry.to_dict())
		json["__time"] = times
	if children.size() > 0:
		for name in children:
			json[name] = children[name].to_dict()
	return json


func _to_string() -> String:
	var json := to_dict()
	var json_string := JSON.print(json, "\t")
	return json_string
