extends Control

var config: ConfigManager = preload("res://config_manager.tres")

onready var v_box_container_primary := $"%VBoxContainerPrimary" as VBoxContainer
onready var toggle_tab_container_button := $"%ToggleTabContainerButton" as Button
onready var tab_container := $"%TabContainer" as TabContainer

func _ready() -> void:
	toggle_tab_container_button.toggle_mode = true
	# warning-ignore:return_value_discarded
	toggle_tab_container_button.connect("toggled", self, "_on_toggle_tab_container_button_toggled")
	tab_container.visible = toggle_tab_container_button.pressed
	OS.window_position = config.last_window_position
	set_window_size()
	get_tree().get_root().set_transparent_background(true)


func _on_toggle_tab_container_button_toggled(is_toggled: bool) -> void:
	tab_container.visible = is_toggled
	set_window_size()


func set_window_size() -> void:
	var style_box := theme.get_stylebox("panel", "background") as StyleBoxFlat
	var margin := style_box.content_margin_bottom * 2
	OS.window_size = v_box_container_primary.rect_size + Vector2.ONE * margin
	if tab_container.visible:
		OS.window_size.y += tab_container.rect_size.y


var mouse_button_is_pressed := false
var dragging_start_position = Vector2()

func _gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.get_button_index() == 1:
			mouse_button_is_pressed = !mouse_button_is_pressed
			dragging_start_position = get_local_mouse_position()


func _process(_delta: float) -> void:
	if mouse_button_is_pressed:
		OS.set_window_position(OS.window_position + get_global_mouse_position() - dragging_start_position)


func _notification(what: int) -> void:
	match what:
		MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
			config.last_window_position = OS.window_position
			get_tree().quit()
