extends CanvasModulate

@export var RSECONDS_PER_GMINUTE: float = 1

@export var r_time: float = 6 * 60 * 60
@export var gradient: GradientTexture1D
@export var min_hour: int = 6
@export var max_hour: int = 24
@export var is_stopped: bool = false
@export var should_apply_modulation: bool = true

var minute: int = 0
var hour: int = self.min_hour
var min_time: float = float(min_hour) * 60 * 60 
var max_time: float = float(max_hour) * 60  * 60 

signal time_changed(hour: int, minute: int)

func _get_game_time() -> float:
	return floorf(self.r_time / 60 * RSECONDS_PER_GMINUTE)

func get_game_minute() -> int:
	return posmod(int(_get_game_time() / RSECONDS_PER_GMINUTE), 60)

func get_game_hour() -> int:
	return posmod(int(_get_game_time() / 60 / RSECONDS_PER_GMINUTE), 24)

func apply_modulation():
	if not should_apply_modulation:
		return
	self.color = \
		self.gradient.gradient.sample(
			(self.r_time - self.min_time) / (self.max_time - self.min_time)
			)
	print("New color:", self.color)

func _on_time_changes() -> void:
	self.minute = get_game_minute()
	self.hour = get_game_hour()
	apply_modulation()

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	self.minute = get_game_minute()
	self.hour = get_game_hour()
	self.min_time = min_hour * 60 * 60
	_on_time_changes()
	time_changed.emit(get_game_hour(), get_game_minute())

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if self.is_stopped or self.r_time >= self.max_time:
		return
	self.r_time = min(self.r_time + (delta * 60 / RSECONDS_PER_GMINUTE), self.max_time)
	if (minute != get_game_minute() or hour != get_game_hour()):
		_on_time_changes()
		time_changed.emit(get_game_hour(), get_game_minute())
