extends Label
# Используем более понятные имена переменных
const STATUS_GOOD := {"text": "Исправно", "color": Color.GREEN, "font_color": Color.BLACK}
const STATUS_BAD := {"text": "Отказ", "color": Color.RED, "font_color": Color.WHITE}
var _is_uf_status_initialized: bool = false
var is_prd_operational: bool = true
var is_uf_operational: bool = false


func _ready() -> void:
    tooltip_text = 'Нет связи с приборами комплекса'
    for prd_module in prd.prd_dict.values():
        prd_module.connect('update_serviceability', Callable(self, 'on_serviceability_changed').bind(prd_module))
    var unit_uf: = network.get_unit_instance('уарэп-эмс')
    unit_uf.connect('data_received', Callable(self, 'on_uf_status_receive'))
    add_theme_color_override("font_color", Color.BLACK)


func on_serviceability_changed(unit_prd_module: Object) -> void:
    var check_service: bool = true
    for prd_module in prd.prd_dict.values():
        if prd_module.unit_yau07.online:
            if not unit_prd_module.serviceability:
                check_service = false
    if check_service != is_prd_operational:
        is_prd_operational = check_service
        _update_serviceability_display()


func _update_serviceability_display() -> void:
    var status := STATUS_GOOD if (is_uf_operational and is_prd_operational) else STATUS_BAD
    text = status.text
    modulate = status.color
    tooltip_text = 'Результаты обобщенного признака работоспособности изделия'
    add_theme_color_override("font_color", status.font_color)


func on_uf_status_receive(unit_uf: Object) -> void:
    var KEMS_B = ((unit_uf.status[0] >> 0) & 1) and ((unit_uf.status[0] >> 3) & 1)
    var EMS_B_1 = ((unit_uf.status[0] >> 1) & 1) and ((unit_uf.status[0] >> 4) & 1)
    var EMS_B_2 = ((unit_uf.status[0] >> 2) & 1) and ((unit_uf.status[0] >> 5) & 1)
    var IP27B = ((unit_uf.status[2] >> 6) & 1)
    var check_service: bool = KEMS_B and EMS_B_1 and EMS_B_2 and IP27B
    if not _is_uf_status_initialized or check_service != is_uf_operational:
        is_uf_operational = check_service
        _update_serviceability_display()
        signaller.emit_signal('update_uf_serviceability', check_service)
        _is_uf_status_initialized = true
