class_name scroll_ecm_params extends ScrollContainer

## Отображает список параметров помехи в таблице.

const CellLineEdit = preload('res://table/ячейка-2.tscn')   ## Ячейка таблицы.
const TableHeader  = preload('res://table/header.tscn')     ## Ячейка заголовок таблицы.
const CellTaggleBtn = preload('res://table/set-toggle.tscn')

const TABLE_HEADER       = [ TableHeader,    TableHeader  ]  ## Описание ряда заголовка.
const TABLE_ROW          = [ CellLineEdit,   CellLineEdit ]  ## Описание ряда.
const TABLE_TAGGLE_BTN   = [ CellLineEdit,   CellTaggleBtn ] ## Описание ряда c кнопкой.
const TABLE_HEADERS_TEXT = ['Параметр',     'Значение'    ]  ## Назания колонок.
const TABLE_COLUMN_SIZE  = [ 370,            85           ]  ## Ширины колонок.

const TABLE_PARAMS       = {
    'powp':      [0, 'Мощность, %', true, 0.0, 100.0],
    'freq':      [1, 'Частота, МГц', true, settings.FREQ_MIN, settings.FREQ_MAX],
    'width':     [2, 'Занимая полоса частот, МГц', true, 0.0, settings.WIDTH_MAX],
    'dur':       [3, 'Длительность импульса, мкс', true, 0.0, settings.DUR_MAX],
    'period':    [4, 'Период повтора, мкс', true, 0.0, settings.PERIOD_MAX],
    'um':        [5, 'Угол места, гр.', true, settings.UM_MIN, settings.UM_MAX] }

const MOD_ROW_INDEX = 6    ## Индекс строки с модуляцией

func init_table():
    for i in TABLE_PARAMS.size(): $table.add_row(TABLE_ROW)
    for key in TABLE_PARAMS.keys():
        var p = TABLE_PARAMS[key]
        $table.set_node_text(0, p[0], p[1])
        $table.set_node_alligment(0, p[0], HORIZONTAL_ALIGNMENT_LEFT)
        $table.set_node_editable(0, p[0], false)
        $table.set_node_editable(1, p[0], false)
        $table.set_node_user_data(1, p[0], key)
        var node = $table.get_node2(1, p[0])
        node.connect('text_submitted', Callable(self, 'on_edit_entry').bind(node))
    $table.add_row(TABLE_TAGGLE_BTN)
    $table.set_node_text(0, MOD_ROW_INDEX, 'Подавление')
    $table.set_node_alligment(0, MOD_ROW_INDEX, HORIZONTAL_ALIGNMENT_LEFT)
    $table.set_node_editable(0, MOD_ROW_INDEX, false)
    var toggle_node = $table.get_node2(1, MOD_ROW_INDEX)
    var toggle_btn = toggle_node.get_children()[0]
    toggle_btn.connect('pressed', on_toggle_btn.bind(toggle_btn))
    toggle_btn.disabled = true
    $table.set_columns_min_size(TABLE_COLUMN_SIZE)
    $table.set_meta('id', 0)
    signaller.connect('interfer_selected', Callable(self, 'on_interfer_selected').bind(toggle_btn))
    signaller.connect('rto_threat_unsel',  Callable(self, 'on_rto_threat_unsel'))


## Called when the node enters the scene tree for the first time.
func _ready():
    call_deferred('init_table')


func on_edit_entry(text : String, entry):
    var ecm = $table.get_meta('ecm')
    if $table.has_meta('ecm') == false: return
    var indexis = $table.get_key_indexes(entry.name)
    var row_i = indexis[1]
    var param = $table.get_node_user_data(1, row_i)
    var p = TABLE_PARAMS[param]
    var old_val = ecm.get_value(param)
    var val = check_value(text, p[3], p[4], old_val)
    ecm.set_value(val, param)
    signaller.emit_signal('interfer_new', ecm)


func check_value(val, min_val, max_val, old_val):
    if val.is_valid_float():
        if float(val) < min_val: return min_val
        if float(val) > max_val: return max_val
        return float(val)
    else: return old_val


func on_interfer_selected(ecm, toggle_btn):
    if ecm != null:
        $table.set_meta('ecm', ecm)
        toggle_btn.disabled = false
    else:
        $table.set_meta('ecm', null)
        toggle_btn.disabled = true
        toggle_btn.button_pressed = false
    on_ecm_update(toggle_btn)


func on_ecm_update(toggle_btn):
    for item in len(TABLE_PARAMS):
        $table.set_node_text(1, item, '')
        $table.set_node_editable(1, item, false)
    if not $table.has_meta('ecm'): return
    var ecm: interfer.Interfer = $table.get_meta('ecm')
    var mnms = tools.get_members_names(ecm)
    for item in ecm['params'].keys():
        mnms.append(item)
    for member_name in mnms:
        if not TABLE_PARAMS.has(member_name): continue
        var p = TABLE_PARAMS[member_name]
        var val = ecm.get_value(member_name)
        $table.set_node_text(1, p[0], '%s' % val)
        $table.set_node_editable(1, p[0], p[2])
    toggle_btn.button_pressed = ecm.modulation


func on_rto_threat_unsel(_th_id):
    for item in range(len(TABLE_PARAMS)):
        $table.set_node_text(1, item, '')
        $table.set_node_editable(1, item, false)


func on_toggle_btn(toggle_btn):
    if not $table.has_meta('ecm'): return
    var ecm: interfer.Interfer = $table.get_meta('ecm')
    ecm.modulation = toggle_btn.button_pressed
