extends TabContainer

const prefab := preload("res://scenes/alarms_screen/alarms_item.tscn")

onready var alarm_items = $"%alarm_items"


func _ready():
#	current_tab = 1
	_replace_alarm_items()

func _replace_alarm_items():
	for item in alarm_items.get_children():
		alarm_items.remove_child(item)
		item.queue_free()
	
	for alarm in Config.flags.alarms:
		spawn_item(alarm)

func spawn_item(alarm):
	var new = prefab.instance()
	new.alarm_res = alarm
	new.connect("edit", self, "_on_item_edit_pressed", [new])
	alarm_items.add_child(new)

func _on_add_button_pressed():
	var new = Alarm.new()
	new.moment = Constants.current_moment()
	edit_alarm(new)
#	if Config.flags.add_alarm(new):
#		spawn_item(new)


func _on_item_edit_pressed(item):
	print("yip yip")
	edit_alarm(item.alarm_res)


var editing_alarm:Alarm setget edit_alarm

func edit_alarm(new:Alarm, show_UI:=true):
	print("edit alarm: ",new)
	editing_alarm = new
	if editing_alarm:
		if show_UI:
			current_tab = 1
		$"%alarm_moment_hour".value = new.moment.hour
		$"%alarm_moment_minute".value = new.moment.minute
		$"%alarm_snoozable".set_pressed_no_signal(new.snooze)
		$"%alarm_play_music".set_pressed_no_signal(new.play_music)
		$"%alarm_weather_override".set_pressed_no_signal(new.override_weather_music)
		$"%alarm_music_override_selection".select(new.weather_music)
		$"%alarm_speak_time".set_pressed_no_signal(new.speak_time)
		
		$"%customs".visible = new.play_music
		$"%override_panel".visible = new.override_weather_music
		
func _on_alarm_play_music_toggled(button_pressed):
	$"%customs".visible =button_pressed
	if editing_alarm:
		editing_alarm.play_music = button_pressed


func _on_alarm_snoozable_toggled(button_pressed):
	if editing_alarm:
		editing_alarm.snooze = button_pressed


func _on_alarm_weather_override_toggled(button_pressed):
	$"%override_panel".visible = button_pressed
	if editing_alarm:
		editing_alarm.override_weather_music = button_pressed

func _on_alarm_moment_hour_value_changed(value):
	if editing_alarm:
		editing_alarm.moment.hour = value


func _on_alarm_moment_minute_value_changed(value):
	if editing_alarm:
		editing_alarm.moment.minute = value


func _on_save_button_pressed():
	if Config.flags.add_alarm(editing_alarm):
		spawn_item(editing_alarm)
	Config.emit_signal("changed")
	editing_alarm = null
	current_tab = 0


func _on_cancel_button_pressed():
	editing_alarm = null
	current_tab= 0


func _on_alarm_speak_time_toggled(button_pressed):
	if editing_alarm:
		editing_alarm.speak_time = button_pressed


func _on_alarm_music_override_selection_selected(idx):
	print("SETTING override music to ",idx," (", Constants.WEATHER.keys()[idx],')')
	if editing_alarm:
		editing_alarm.weather_music = idx
