extends Control

@export var textures: Array
@export var unit_name: String = ''


enum STATE_VAL {
    NONE = 0,
    GOOD = 1,
    ERROR = 2 }


signal pressed(control: PanelContainer)


func _on_button_pressed():
    emit_signal('pressed', self)


@export var state: int:
    set(v):
        state = tools.clip_value(v, 0, textures.size() - 1)
        if is_inside_tree():
            $margin/vbox/grid/state.texture = textures[v]


@export var fname: String:
    set(v):
        fname = v
        if is_inside_tree():
            $margin/vbox/grid/fname.text = v


@export var rname: String:
    set(v):
        rname = v
        if is_inside_tree():
            $margin/vbox/grid/rname.text = v


@export var alignment: int:
    set(v):
        if is_inside_tree():
            $margin/vbox.alignment = v


func _ready() -> void: call_deferred('_on_resized')


func _on_resized() -> void:
    $rect.size = size
    $margin.size = size


func _enter_tree() -> void:
    if Engine.is_editor_hint(): return
    var unit_any: = network.get_unit_instance(unit_name)
    unit_any.connect('data_received', Callable(self, 'on_data_received'))
    unit_any.connect('line_changed',  Callable(self, 'on_line_changed'))
    $margin/vbox.alignment = alignment
    $margin/vbox/grid/fname.text = fname
    $margin/vbox/grid/rname.text = rname
    $margin/vbox/grid/state.texture = textures[state]


func _exit_tree() -> void:
    if Engine.is_editor_hint(): return
    var unit_any: = network.get_unit_instance(unit_name)
    unit_any.disconnect('data_received', Callable(self, 'on_data_received'))
    unit_any.disconnect('line_changed', Callable(self, 'on_line_changed'))
