@tool
extends TextureButton

@onready var tween: Tween
@export var state_colors: Array


func _ready():
    toggle_mode = true
    focus_mode = Control.FOCUS_ALL
    connect("focus_entered", _on_focus_entered)
    connect("focus_exited", _on_focus_exited)


func _enter_tree() -> void:
    if has_node("label"):
        $label.self_modulate = state_colors[state]


func update_progress_bar(target_value) -> void:
    if tween:
        tween.kill()
    tween = create_tween()
    tween.tween_property($control_progress, "value", target_value, 0.3)


func _on_toggled(toggled_on):
    if has_node("frame"):
        $frame.visible = toggled_on


func _on_focus_entered():
    button_pressed = true
    #enter_press()  TODO: Пока что без выбора прибора


func _on_focus_exited():
    pass


func enter_press():
    var enter_event = InputEventAction.new()
    enter_event.action = "ui_accept"
    enter_event.pressed = true
    Input.parse_input_event(enter_event)


func _on_settings_changed():
    if not is_inside_tree(): return
    var white_color = ProjectSettings.get_setting('Схема прибора. Белый цвет', Color.LIGHT_GRAY)
    var black_color = ProjectSettings.get_setting('Схема прибора. Чёрный цвет', Color.BLACK)
    $pic_functional.material.set('shader_parameter/white', white_color)
    $pic_functional.material.set('shader_parameter/black', black_color)


@export var state: int:
    set(v):
        v = 0 if v < 0 else v % state_colors.size()
        state = v
        if is_inside_tree() and has_node("label"):
            $label.self_modulate = state_colors[v]


@export var progress_value: float = 0.0:
    set(v):
        progress_value = v

        if is_inside_tree():
            update_progress_bar(v)
            var max_val = $control_progress.get('max_value')
            var percentage = (v / max_val) * 100.0
            $control_progress.tooltip_text = 'Процесс контроля %01d%%' % percentage


@export var progress_visible: bool:
    set(v):
        progress_visible = v
        if is_inside_tree():
            $control_progress.visible = v


@export var progress_max_value: int:
    set(v):
        progress_max_value = v
        if is_inside_tree():
            $control_progress.max_value = v


@export var progress_min_value: int:
    set(v):
        progress_min_value = v
        if is_inside_tree():
            $control_progress.min_value = v


@export var show_functional: bool:
    set(v):
        show_functional = v
        if is_inside_tree():
            $pic_functional.visible = v
