class_name DayNightController
extends Node

const TIME_OPTION_SUNRISE: int = 0
const TIME_OPTION_DAY: int = 1
const TIME_OPTION_SUNSET: int = 2
const TIME_OPTION_NIGHT: int = 3

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
var _current_time_option_index: int = -1

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)
	UIEvents.time_option_item_changed.connect(_time_option_changed)

	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:
	var time_option_index: int = get_time_option_index(currtime)
	if time_option_index != _current_time_option_index:
		_current_time_option_index = time_option_index
		UIEvents.day_time_option_changed.emit(time_option_index)

	emit_signal("time_changed", currtime)
	UIEvents.day_time_changed.emit(currtime, get_time_string())

func get_time_option_index(currtime: float) -> int:
	if currtime >= environment_config.night or currtime < environment_config.sunrise:
		return TIME_OPTION_NIGHT
	if currtime < environment_config.day:
		return TIME_OPTION_SUNRISE
	if currtime < environment_config.sunset:
		return TIME_OPTION_DAY
	return TIME_OPTION_SUNSET

func _time_option_changed(index: int) -> void:
	match index:
		TIME_OPTION_SUNRISE:
			set_time(environment_config.sunrise)
		TIME_OPTION_DAY:
			set_time(environment_config.day)
		TIME_OPTION_SUNSET:
			set_time(environment_config.sunset)
		TIME_OPTION_NIGHT:
			set_time(environment_config.night)

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

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