extends MarginContainer

export(Dictionary) var sections: Dictionary = {
	"Home": load("res://scenes/sections_content/home/home.tscn"),
	"Following": load("res://scenes/sections_content/following/following.tscn"),
}
export(PackedScene) var main_region: PackedScene
export(int) var main_region_margin: int = 5


onready var _tabs_node: TabContainer = find_node("Tabs")
onready var sections_order: PoolStringArray = Data.get_sections_order()


func _ready() -> void:
	var extensions: Dictionary = Extensions.load_extensions()
	for section_name in extensions:
		if section_name and extensions[section_name]:
			sections[section_name] = extensions[section_name]
	add_main_region()


func _exit_tree() -> void:
	Data.save_sections_order(sections_order)


func add_main_region() -> void:
	var margin_container := MarginContainer.new()
	margin_container.add_constant_override("margin_top", main_region_margin)
	margin_container.add_constant_override("margin_bottom", main_region_margin)
	margin_container.add_constant_override("margin_left", main_region_margin)
	margin_container.add_constant_override("margin_right", main_region_margin)
	
	var region: MainRegion = main_region.instance()
	region.connect("selected_section_changed", self,
			"_on_MainRegion_selected_section_changed", [margin_container])
	region.connect(
			"sections_reordered", self, "_on_MainRegion_sections_reordered")
	
	margin_container.add_child(region)
	_tabs_node.add_child(margin_container)
	region.init(sections, sections_order)


func _on_MainRegion_selected_section_changed(section_name: String,
		container: Control) -> void:
	""" Sets the text of the tab `container` is in """
	_tabs_node.set_tab_title(container.get_position_in_parent(), section_name)


func _on_MainRegion_sections_reordered(region: MainRegion) -> void:
	"""
	When the order of the sections is updated in one `MainRegion`, that is
	saved as the order that should be used in the future and all other
	`MainRegion`s are updated to use that order
	"""
	sections_order = region.get_sections_order()
	for child in _tabs_node.get_children():
		var a_region: MainRegion = child.get_child(0)
		if not a_region is MainRegion:
			push_warning("MainRegion not found")
			continue
		for position in range(len(sections_order)):
			a_region.set_section_position(sections_order[position], position)
