@tool
class_name pribor_afsp extends 'res://scenes/контроль/прибор.gd'

@export var prefix_path: String = ''                 ## Должно быть в JSON
@export var this_afsp_name: String = ''              ## Должно быть в JSON
@export var unit_name: StringName= ''                ## Должно быть в settings.gd
@export var settings_path_to_url: String = ''        ## Должно быть в ProjectSettings
@export var settings_path_to_wait_time: String = ''  ## Должно быть в ProjectSettings

static var json_conv: JSON = JSON.new()
static var node_maper = load('res://scenes/контроль/node-maper.gd')
var ctrl_pos = 0

# SystemName: "gen" DevList - там состояние связи с генератором по кан шине


func _ready() -> void:
    ProjectSettings.connect('settings_changed', on_settings_chaged)
    on_settings_chaged()


func on_settings_chaged():
    $request.request_url = ProjectSettings.get_setting('application/config/%s' % settings_path_to_url)
    $request/timer.wait_time = float(ProjectSettings.get_setting('application/config/%s' % settings_path_to_wait_time))
    tools.allways($request.request_url != null)


func _on_request_completed(result, _response_code, headers, body: PackedByteArray):

    var unit_instance: = network.get_unit_instance(unit_name)

    if result != 0:
        var rs = $request.get_result_string(result)
        log.error('\"%s\"' % rs)
        if unit_instance.online:
            unit_instance.online = false
            unit_instance.emit_signal('line_changed', unit_instance)
        return

    var json_str: String = body.get_string_from_utf8()
    if not json_str:
        push_error('не удаётся получить строку utf8 из данных (%s)' % headers)
        if unit_instance.online:
            unit_instance.online = false
            unit_instance.emit_signal('line_changed', unit_instance)
        return

    var rc: = json_conv.parse(json_str)
    if rc != Error.OK:
        var err: = json_conv.get_error_message()
        push_error('разбор json прерван - \"%s\" (%s)' % [err, headers])
        if unit_instance.online:
            unit_instance.online = false
            unit_instance.emit_signal('line_changed', unit_instance)
        return

    var pp = []
    tools.map_solid_to_array(prefix_path, pp)
    var ret_val = [null, false, 0]
    var pp_copy = pp.duplicate(true)
    tools.get_value_by_path(json_conv.data, pp, ret_val)
    if not ret_val[1]:
        push_error('путь %s не найден (%s)' % [pp_copy, ret_val[2]])
        return

    var received_afsp_name: StringName = ret_val[0]

    if this_afsp_name != received_afsp_name:
        # TODO: Сюда попадаем, когда приходит от другого борта
        #push_error('не известное устройство: \"%s\", ожидадось: \"%s\"' % [received_afsp_name, this_afsp_name])
        return

    unit_instance.rx_tick = Time.get_ticks_msec()
    if not unit_instance.online:
        unit_instance.online = true
        unit_instance.emit_signal('line_changed', unit_instance)

    for child in $bort.get_node('konverter/grid').get_children():
        node_maper.map_value_to_item(json_conv.data, child, 'value0')
        node_maper.map_value_to_item(json_conv.data, child, 'value1')
        node_maper.map_value_to_item(json_conv.data, child, 'value2')
        node_maper.map_error_codes_to_item(json_conv.data, child, 'state', 0)
    for child in $bort.get_node('antenna1/grid').get_children():
        node_maper.map_value_to_item(json_conv.data, child, 'value0')
        node_maper.map_value_to_item(json_conv.data, child, 'value1')
        node_maper.map_error_codes_to_item(json_conv.data, child, 'state', 0)
    for child in $bort.get_node('antenna2/grid').get_children():
        node_maper.map_value_to_item(json_conv.data, child, 'value0')
        node_maper.map_value_to_item(json_conv.data, child, 'value1')
        node_maper.map_error_codes_to_item(json_conv.data, child, 'state', 0)
    for child in $bort.get_children():
        node_maper.map_value_to_item(json_conv.data, child, 'value0')
        node_maper.map_value_to_item(json_conv.data, child, 'value1')
        node_maper.map_error_codes_to_item(json_conv.data, child, 'state', 0)


## Вызывается при клике мыши на элементе.
## [param block_a] - Кликнутый элемент.
func _on_item_pressed(block_a: Control):
    var metas = block_a.get_meta_list()
    for n in metas:
        var _v = block_a.get_meta(n)
