class_name DayNightController
extends Node

var environment_config: EnvironmentConfig

#Multiply for debug
@export var time_scale: float = 1.0

@export var paused: bool = false

signal time_changed(time: float)

var current_time: float = 0.0

func _init(environmentconfig: EnvironmentConfig) -> void:
	environment_config = environmentconfig
	
func _ready() -> void:
	#connect events
	UIEvents.set_day_time.connect(_on_set_day_time)
	UIEvents.toggle_pause_daytime.connect(_on_toggle_pause_daytime)

	current_time = environment_config.start_time
	update_time(current_time)

func _process(delta: float) -> void:
	if paused or environment_config.day_duration <= 0.0:
		return

	var increment: float = (delta * time_scale) / environment_config.day_duration
	current_time = wrapf(current_time + increment, 0.0, 1.0)

	update_time(current_time)

func get_time_string() -> String:
	var total_minutes: int = int(current_time * 1440.0)
	@warning_ignore("integer_division")
	var hours: int   = int(total_minutes / 60)
	var minutes: int = total_minutes % 60
	return "%02d:%02d" % [hours, minutes]

func set_time(t: float) -> void:
	current_time = wrapf(t, 0.0, 1.0)
	update_time(current_time)

func update_time(currtime: float) -> void:
	emit_signal("time_changed", currtime)
	UIEvents.day_time_changed.emit(currtime, get_time_string())

func _on_set_day_time(value: float) -> void:
	set_time(value)

func _on_toggle_pause_daytime(value: bool) -> void:
	paused = value
