extends VBoxContainer


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


onready var task_name_line_edit := $"%TaskNameLineEdit" as LineEdit
onready var time_label := $"%TimeLabel" as Label
onready var start_button := $"%StartButton" as Button
onready var timer := $"%Timer" as Timer
onready var audio_stream_player := $"%AudioStreamPlayer" as AudioStreamPlayer

var current_time_entry: TimeEntry

func _ready() -> void:
	# warning-ignore:return_value_discarded
	timer.connect("timeout", self, "_on_timer_timeout")
	start_button.hint_tooltip = tr(Consts.START)
	start_button.toggle_mode = true
	# warning-ignore:return_value_discarded
	start_button.connect("toggled", self, "_on_start_button_toggled")
	task_name_line_edit.text = config.current_task_name
	# warning-ignore:return_value_discarded
	task_name_line_edit.connect("text_changed", self, "_on_task_name_line_edit_text_changed")
	# warning-ignore:return_value_discarded
	config.connect("time_sheet_loaded", self, "_on_time_sheet_loaded")
	update_timer_state()


func _on_timer_timeout() -> void:
	config.timesheet.update()
	time_label.text = current_time_entry.get_period()


func _on_start_button_toggled(_is_on: bool) -> void:
	if config.sound_fx_on:
		audio_stream_player.play()
	if current_time_entry != null:
		# warning-ignore:return_value_discarded
		config.timesheet.stop_entry(task_name_line_edit.text)
	else:
		# warning-ignore:return_value_discarded
		config.timesheet.add_entry(task_name_line_edit.text)


func _on_task_name_line_edit_text_changed(new_text: String) -> void:
	config.current_task_name = new_text
	update_timer_state()


func _on_time_sheet_loaded():
	update_timer_state()

func update_timer_state() -> void:
	current_time_entry = config.timesheet.get_active_entry_from_name(config.current_task_name)
	if current_time_entry:
		set_button_as_started()
	else:
		set_button_as_stopped()


func set_button_as_stopped() -> void:
	start_button.set_pressed_no_signal(false)
	start_button.hint_tooltip = tr(Consts.START)
	time_label.text = Consts.NO_TIME
	start_button.theme_type_variation = Consts.THEME_OVERRIDE_START
	timer.stop()


func set_button_as_started() -> void:
	start_button.set_pressed_no_signal(true)
	start_button.hint_tooltip = tr(Consts.STOP)
	start_button.theme_type_variation = Consts.THEME_OVERRIDE_STOP
	timer.start()
