@tool
extends Control

var color_on := Color(0, 128, 0)
var color_off := Color(0, 0, 0)
var last_delta := 0.0
@export_range(0.1, 120.0) var display_sec := 5.0
@export var stretch_display := false

var morse_step_perc := 0.45


func _draw_morse_rect(x: float, width: float, state: bool):
	var rect := Rect2(max(x, 0.0), morse_step_perc * size.y, width, (0.5 - morse_step_perc) * size.y)
	draw_rect(rect, color_on if state else color_off, true, -1.0, true)
	
func _draw():
	# black background
	draw_rect(Rect2(0.0, 0.0, size.x, size.y), Color.BLACK)
	
	# in editor we only want a black rectangle
	if Engine.is_editor_hint():
		return

	var morse_on := MorseState.curr_state
	var first_time := Time.get_ticks_msec() - MorseState.last_change
	var curr_x := float(size.x)
	
	var px_per_s := 0.0
	if not stretch_display:
		px_per_s = size.x / display_sec
	else:
		px_per_s = size.x / (Time.get_ticks_msec() - MorseState.start_time) * 1000.0
	
	for n in [-1] + range(MorseState.states.size() - 1, -1, -1):
		var duration := first_time if n == -1 else MorseState.states[n]
		var rect_width: float = min(duration / 1000.0 * px_per_s, curr_x)
		curr_x -= rect_width
		if morse_on:
			# at the moment we only draw the morse rects
			_draw_morse_rect(curr_x, rect_width, morse_on)
		morse_on = not morse_on
		if curr_x <= 0.0:
			break

func _process(_delta):
	last_delta += _delta
	queue_redraw()