extends MarginContainer

onready var tab_buttons = $"%tab_buttons"
onready var weather_api_node = $WeatherAPINode

onready var backgrounds = get_tree().get_nodes_in_group("background")
onready var foreground = $foreground
onready var screens = $"%screens"
onready var time_talker = $"time talker"
onready var sleep_mode = $sleep_mode
onready var minute_timer = $"minute timer"

const version := '1.0'
const linkbacks := true

var audio_button
var weather_data := []

func _ready():
	if not linkbacks:
		get_tree().call_group("linkbacks", "hide")
		get_tree().call_group("linkbacks", "set_text", '')


	if OS.get_name() in ['Android', 'IOS']:
		get_tree().set_screen_stretch( SceneTree.STRETCH_MODE_2D, SceneTree.STRETCH_ASPECT_EXPAND, Vector2(ProjectSettings.get_setting("display/window/size/width"), ProjectSettings.get_setting("display/window/size/height")))

	Config.connect("changed", self, "_on_config_changed")
	_on_config_changed(true)
	print(screens)
	audio_button = screens.tabs_holder.get_child(0).audio
	print(audio_button)
	$WeatherAPINode.location = Config.flags.location
	_on_hourly_weather_timer_timeout()
	_on_minute_timer_timeout()
	var seconds = Time.get_time_dict_from_system()['second']
	minute_timer.start(60-seconds)


func _on_config_changed(skip_api_update:=false):
	
	if !skip_api_update and (weather_api_node.location != Config.flags.location or weather_api_node.api_key != Config.flags.api_key):
		weather_api_node.api_key = Config.flags.api_key
		weather_api_node.location = Config.flags.location
		_on_hourly_weather_timer_timeout()
	else:
		weather_api_node.api_key = Config.flags.api_key
		weather_api_node.location = Config.flags.location

	_check_dark_mode(Time.get_time_dict_from_system())

func _on_TabContainer_tab_selected(tab):
	var x := 0
	if !tab_buttons:
		return
	for item in tab_buttons.get_children():
		item.pressed = x == tab
		x += 1

func _notification(what):
	if what == NOTIFICATION_WM_QUIT_REQUEST or what == NOTIFICATION_APP_PAUSED or what == NOTIFICATION_WM_FOCUS_OUT:
		Config.save_flags()
	if what == NOTIFICATION_WM_QUIT_REQUEST:
		get_tree().quit()

func tween_background(color:Color, duration := 0.75):
	for background in backgrounds:
		var tween = get_tree().create_tween()
		tween.tween_property(background, 'color', color, duration)
		tween.play()

func _on_hourly_weather_timer_timeout():
	weather_api_node.get_forecast()

func _on_WeatherAPINode_received_forecast(json):
	var WC = Constants.WEATHER.UNKNOWN
	print('weather update: ',json)
	if json != null and not json.get('error'):
		weather_data.append(json)
		WC = json['current']['condition']['code']
	get_tree().call_group("hourly_weather_updates", "hourly_weather_update", json)
	var weather = Constants.code_to_weather(WC)
	tween_background(Constants.weather_to_color(weather))

func set_transition(stage:float):
	foreground.material.set_shader_param('transition', stage)

func _on_minute_timer_timeout():
	var time = Time.get_time_dict_from_system()
	get_tree().call_group("minute_timer_updates", "minute_timer_update", time)
	_check_dark_mode(time)
	minute_timer.start(60.0)
	
func _check_dark_mode(time):
	var ctrans = foreground.material.get_shader_param('transition')
	var target = 0.0
	if Config.flags.automatic_dark_mode and (time['hour'] >= 20 or time['hour'] <= 6):
		print('go')
		target = 1.0
	if ctrans != target:
		var tween = get_tree().create_tween()
		tween.tween_method(self, "set_transition", 1.0-target, target, 2.0)
		tween.play()



func _on_audio_toggled(button_pressed):
	if button_pressed:
		var weather = Constants.WEATHER.UNKNOWN
		if len(weather_data) > 0:
			weather = Constants.code_to_weather(weather_data[-1]['current']['condition']['code'])
		time_talker.play(Constants.current_moment(), Time.get_date_dict_from_system()['weekday'], weather)
	else:
		time_talker.stop(2.5)


func _on_time_talker_finished():
	pass # Replace with function body.
	audio_button.pressed = false


func _on_hide_sleepmode_pressed():
	sleep_mode.hide()


func _on_tab_button_pressed(idx:int):
	if screens:
		screens.switch_tab(idx)




func _on_credits_button_pressed():
	if linkbacks:
		OS.shell_open("https://lisanne.gay/")
