extends ScrollContainer


## Отображает список помех в таблице.
const CellLineEdit = preload('res://table/ячейка-2.tscn')  ## Ячейка таблицы.
const TableHeader  = preload('res://table/header.tscn')    ## Ячейка заголовок таблицы.
const EmitLed      = preload('res://scenes/frame-threats/emit-led.tscn')     ## Ячейка символа излучения

const TABLE_HEADER       = [ TableHeader,   TableHeader,     TableHeader ,     TableHeader ,     TableHeader ]   ## Описание ряда заголовка.
const TABLE_ROW          = [ CellLineEdit,  CellLineEdit,    CellLineEdit ,    CellLineEdit ,    EmitLed ]  ## Описание ряда.
const TABLE_HEADERS_TEXT = ['№',       'Название',  'Пеленг',  'Состояние'  ,  'Излучение'  ]         ## Заголовки таблицы.
const TABLE_COLUMN_SIZE  = [ 65,            80,             80,             130  ,             90  ]              ## Ширины колонок.


## Состояние выполнения сеанса помехи
const INTERFER_STATE = {
    0: 'Подготовка',
    1: 'Выполняется',
    2: 'Ошибка',
    3: 'Занято',
    4: 'Неисправность',
    5: '' }


## Названия помех
const INTERFER_NAMES = {
    'off': 'Откл',
    'mchm1': 'МЧМ-1',
    'srni1': 'СРН-И1',
    'srnm2': 'СРН-М2',
    'srngps': 'СРН-GPS',
    'pdm4': 'ПД-М4',
    'pdm2': 'ПД-М2',
    'lchm1': 'ЛЧМ-1',
    'lchm2': 'ЛЧМ-2',
    'pdm4s': 'ПД-М4С',
    'pdchm': 'ПД-ЧМ',
    'svi1': 'СВ-И1',
    'k1': 'K1',
    'svm2': 'СВ-М2',
    'ozp1': 'ОЗП-1',
    'elrs': 'ЕЛРС' }


var SIGNALS_CONNECTIONS = [
    [signaller,  'interfer_new',           'on_interfer_new'],
    [signaller, 'interfer_off',           'on_interfer_off'],
    [signaller, 'rto_threat_unsel',       'on_rto_threat_unsel'],
    [signaller, 'rto_threat_sel',         'on_rto_threat_sel'],
    [interfer,  'interfer_update',        'on_interfer_update'],
    [interfer,  'interfer_recommendate',  'on_interfer_recommendate'],
    [interfer,  'interfer_resized',       'on_interfer_resized'] ]


## Индексы колонок
const COLUMN_NUMBER = 0
const COLUMN_NAME = 1
const COLUMN_AOA = 2
const COLUMN_STATE = 3
const COLUMN_EMITED = 4
const TABLE_TEXT_ROWS = 4

var course = 0.0                        ## Курс корабля
var color_emit: Color
var signal_conections: Array
var ecms: Dictionary                    ## Словарь с помехами

func on_rto_threat_unsel(_th_id, _tbl_index): $table.clear_rows_selected()


## Вызывается при нажатии указателем мыши на выбранный ряд.
func on_row_pressed(i_row: int):
    $table.clear_rows_selected()
    $table.set_row_selected(i_row, true)
    var ecm = $table.get_node_user_data(0, i_row)
    if interfer.thrs.has(ecm.ispp):
        signaller.emit_signal('rto_threat_sel', interfer.thrs[ecm.ispp])
    else:
        if interfer.fs.has(ecm.ispp):
            signaller.emit_signal('fs_selected', ecm)
        signaller.emit_signal('interfer_selected', ecm)


## Вызывается при выборе цели
func on_rto_threat_sel(th_id: int, table_index):
    var ecm_ispp = interfer.thrs.find_key(th_id)
    var ecm = null
    if ecm_ispp != null:
        var i_row = table_index[int(ecm_ispp)]
        ecm = $table.get_node_user_data(0, i_row)
        $table.clear_rows_selected()
        $table.set_row_selected(i_row, true)
    else:
        $table.clear_rows_selected()
    signaller.emit_signal('interfer_selected', ecm)


# Called when the node enters the scene tree for the first time.
func _ready():
    var table_index: = Dictionary()
    for item in SIGNALS_CONNECTIONS:
        item.append(table_index)
    $table.connect('row_pressed', Callable(self, 'on_row_pressed'))
    call_deferred('init_table')
    var unit_nav = network.get_unit_instance('навигация')
    unit_nav.connect('data_received', on_navi_data_received)
    ProjectSettings.connect('settings_changed', on_settings_changed)
    signaller.connect('режим_работа', connect_all)
    signaller.connect('режим_контроль', disconnect_all)
    signaller.connect('режим_журнал', disconnect_all)
    signaller.connect('режим_эмс', disconnect_all)
    signaller.connect('режим_эмс2', disconnect_all)
    signaller.connect('режим_настройки', disconnect_all)
    connect_all()


func init_table():
    $table.set_header(TABLE_HEADER)
    $table.set_header_text(TABLE_HEADERS_TEXT)
    $table.set_columns_min_size(TABLE_COLUMN_SIZE)
    $table.pin_header(self, get_parent())


func on_interfer_update(ecm, table_index):
    var row = map_th_to_row(ecm)
    if not table_index.has(ecm.ispp): return
    var i_row = table_index[ecm.ispp]
    $table.set_row_text(i_row, row)
    var power: bool = prd.get_fs_power(ecm.nmfs)
    var emit_node = $table.get_node2(COLUMN_EMITED, i_row)
    var emit_txr = emit_node.get_node('texture-led')
    emit_txr.position.x = 40.0
    ecm.active = power
    if power:
        emit_txr.visible = true
        emit_txr.self_modulate = color_emit
    else:
        emit_txr.visible = false


func on_interfer_new(ecm, table_index):
    var row = map_th_to_row(ecm)
    if table_index.has(ecm.ispp):
        var i_row = table_index[ecm.ispp]
        $table.set_row_text(i_row, row)
    else:
        var i_row = $table.get_rows_count()
        $table.add_row(TABLE_ROW)
        $table.set_row_text(i_row, row)
        disable_edit($table, TABLE_TEXT_ROWS, i_row)
        $table.set_node_user_data(0, i_row, ecm)
        table_index[ecm.ispp] = i_row
        $table.clear_rows_selected()
        $table.set_row_selected(i_row, true)
    if not interfer.auto_enabled:
        signaller.emit_signal('interfer_selected', ecm)


func on_interfer_off(ecm, table_index):
    if not table_index.has(ecm.ispp):
        return
    var i_row = table_index[ecm.ispp]
    $table.remove_row(i_row)
    rehash(table_index)
    var sel_rows: Array
    $table.get_selected_rows(sel_rows)
    if not len(sel_rows):
        signaller.emit_signal('interfer_selected', null)


## Перестраивает индекс таблицы. Вызывать при удалении строки
func rehash(table_index: Dictionary):
    table_index.clear()
    var rows_count = $table.get_rows_count()
    for i_row in rows_count:
        var item = $table.get_node2(0, i_row)
        table_index[int(item.text)] = i_row


## Преобразует цель в строку таблицы
func map_th_to_row(ecm) -> Array:
    var row: = Array()
    row.resize(TABLE_ROW.size() - 1)
    row[COLUMN_NUMBER] = '%s' % ecm.ispp
    row[COLUMN_NAME] = ''
    if INTERFER_NAMES.has(ecm.krp):
        row[COLUMN_NAME] = '%s' % INTERFER_NAMES[ecm.krp]
    var aoa = ecm.kni + course
    if aoa > 360.0:
        aoa -= 360.0
    row[COLUMN_AOA] = '%5.1f' % aoa
    row[COLUMN_STATE] = ''
    if INTERFER_STATE.has(ecm.svk):
        row[COLUMN_STATE] = '%s' % INTERFER_STATE[ecm.svk]
    return row


func on_interfer_recommendate(ecm, _tbl_index):
    var sel_rows: Array
    $table.get_selected_rows(sel_rows)
    if not len(sel_rows): return
    var sel_ecm = $table.get_node_user_data(0, sel_rows[0])
    if ecm == sel_ecm:
        signaller.emit_signal('interfer_selected', ecm)


func on_navi_data_received(data: Dictionary):
    course = data.get('k', 0.0)


func on_settings_changed():
    var json_col = ProjectSettings.get_setting('application/config/%s' % 'Цвет кнопки \"Подавление\"', '[1.0, 1.0, 1.0, 1.0]')
    var arr_col = JSON.parse_string(json_col)
    color_emit = Color(arr_col[0], arr_col[1], arr_col[2], arr_col[3])


## Отключает возможность редактирования LineEdit в таблице.[br]
## [param tbl] - таблица,[br]
## [param num_col] - номер колонки,[br]
## [param i_row] - номер столбца.[br]
func disable_edit(tbl, num_col: int, i_row: int):
    for col in num_col:
        var node: LineEdit = tbl.get_node2(col, i_row)
        node.editable = false


func connect_all() -> void:
    signal_conections.clear()
    var table_index = SIGNALS_CONNECTIONS[0][3]
    for item in SIGNALS_CONNECTIONS:
        var proc = Callable(self, item[2]).bind(item[3])
        var rc = item[0].connect(item[1], proc)
        if rc == Error.OK:
            signal_conections.append([item[0], item[1], proc])
        else:
            var ers = error_string(rc)
            push_error('%s: %s %s %s' % [ers, item[0], item[1], item[2]])
    signaller.emit_signal('connect_work_signal')
    for ecm in ecms.values():
        on_interfer_new(ecm, table_index)


func disconnect_all() -> void:
    var table_index = SIGNALS_CONNECTIONS[0][3]
    for item in signal_conections:
        item[0].disconnect(item[1], item[2])
    signal_conections.clear()
    $table.clear_rows()
    table_index.clear()


func on_interfer_resized(ecms_dic: Dictionary, _tbl_index) -> void:
    ecms = ecms_dic
