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

@export var prefix_path: String = ''                 ## Должно быть в JSON
@export var this_bpo1_name: String = ''              ## Должно быть в JSON
@export var this_bpo2_name: String = ''              ## Должно быть в JSON
@export var unit_name1: StringName= ''               ## Должно быть в settings.gd
@export var unit_name2: StringName= ''               ## Должно быть в settings.gd
@export var settings_path1_to_url: String = ''       ## Должно быть в ProjectSettings
@export var settings_path2_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 = 110


var bort_to_node_name = {}
var bort_to_unit_name = {}



func _ready() -> void:
    ProjectSettings.connect('settings_changed', on_settings_changed)
    on_settings_changed()
    find_labels(self)


func on_settings_changed():
    bort_to_node_name.merge({this_bpo1_name: 'grid_bpo_a1', this_bpo2_name: 'grid_bpo_a2'}, true)
    bort_to_unit_name.merge({this_bpo1_name: unit_name1, this_bpo2_name: unit_name2})
    $request1.request_url = ProjectSettings.get_setting('application/config/%s' % settings_path1_to_url)
    $request1/timer.wait_time = float(ProjectSettings.get_setting('application/config/%s' % settings_path_to_wait_time))
    $request2.request_url = ProjectSettings.get_setting('application/config/%s' % settings_path2_to_url)
    $request2/timer.wait_time = float(ProjectSettings.get_setting('application/config/%s' % settings_path_to_wait_time))
    assert($request1.request_url != null)
    assert($request2.request_url != null)


func _on_request_completed(result, _response_code, headers, body: PackedByteArray):
    if result != 0:
        var rs = $request1.get_result_string(result)
        push_error('\"%s\"' % rs)
        return

    var json_str: = body.get_string_from_utf8()
    if not json_str:
        push_error('не удаётся получить строку из utf8-данных (%s)' % headers)
        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])
        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

    if not bort_to_node_name.has(ret_val[0]):
        push_error('не известное устройство: \"%s\"' % ret_val[0])
        return

    var node_name = bort_to_node_name[ret_val[0]]
    var bort_node = get_node(node_name)

    var unit_name = bort_to_unit_name[ret_val[0]]
    var unit_instance = network.get_unit_instance(unit_name)
    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 item in bort_node.get_children():
        node_maper.map_value_to_item(json_conv.data, item, 'state')

    var items = get_tree().get_nodes_in_group('управляется-по-шине-1')
    for node in items:
        if node.state == 1:
            $yas_bpo_a1.state = 1
            break
    items = get_tree().get_nodes_in_group('управляется-по-шине-2')
    for node in items:
        if node.state == 1:
            $yas_bpo_a2.state = 1
            break
    items = get_tree().get_nodes_in_group('потребитель-питания')
    for node in items:
        if node.state == 1:
            $mod_pit_g1.state = 1
            break


func find_labels(node1: Node):
    if node1 is Label:
        if node1.name in ["lbl_rname", "rname"]:
            if not node1.has_meta("tooltip_set"):
                ctrl_pos += 1
                var box_number = ceili(float(ctrl_pos) / 10.0)
                var position_number = ctrl_pos % 10
                if position_number == 0:
                    position_number = 10
                node1.tooltip_text = "Ящик - %d, Позиция - %d" % [box_number, position_number]
                node1.mouse_filter = Control.MOUSE_FILTER_STOP
                node1.set_meta("tooltip_set", true)
    for child in node1.get_children():
        find_labels(child)
