extends Node

var id_array: Array                 # Массив id целей
var interfers : Dictionary          # Словарь целей
var msg_counter : int = 0           # Счётчик отправленных пакетов
var g_table                         # таблица с помехами


const TableCellType1 = preload('res://ячейка-1.tscn')
const TableCellType2 = preload('res://кнопка-3.tscn')
const TableCellType3 = preload('res://кнопка-4.tscn')
const TableCellType4 = preload('res://заголовок.tscn')
const TableCellType5 = preload('res://ячейка-2.tscn')
const TableCellType6 = preload('res://кнопка-5.tscn')
const TableHeader = preload('res://table/header.tscn')

# Индекс колонки:                 0                1                2                3                4                5                6
const TABLE_HEADERS           = [ 'Индекс',        'Состояние',     'Помеха',       'Мощность',      'Кур. уг.',      'Частота',       'Ш. диап.']
const TABLE_HEADER_TYPES      = [ TableHeader,  TableHeader,  TableHeader,  TableHeader,  TableHeader,  TableHeader,  TableHeader]
const TABLE_HEADER_ALIGNMENTS = [ HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER]
const TABLE_ROW_TYPES         = [ TableCellType1,  TableCellType6,  TableCellType1,  TableCellType1,  TableCellType1,  TableCellType1,  TableCellType1]
const TABLE_ROW_ALIGNMENTS    = [ HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER,   HORIZONTAL_ALIGNMENT_CENTER]
const TABLE_COLUMN_SIZES      = [ 82,              150,             82,              100,              82,              90,              150]

const COLUMN_ISPP    = 0   # Индекс сейанса постановки помехи
const COLUMN_SVK     = 1   # Состояние выполнения помехи
const COLUMN_KRP     = 2   # Помеха
const COLUMN_POWP    = 3   # Мощность излучения
const COLUMN_KNI     = 4   # Курсовой угол
const COLUMN_FREQ    = 5   # Частота
const COLUMN_WIDTH   = 6   # Ширина диапазона


# Индексы колонок, которым можно задавать выравнивание текста
const TABLE_ALLIGNED_COLUMNS  = [
    COLUMN_ISPP,
    COLUMN_KRP,
    COLUMN_POWP,
    COLUMN_KNI,
    COLUMN_FREQ,
    COLUMN_WIDTH, ]

# Состояние выполнения команды поставновки помехи
const SVK = ['Подготовка', 'Выполнено', 'Ошибка', 'Занято', 'Неисправно']

# Номера колонок
const COLUMN_OPT = [[COLUMN_SVK, SVK]]
const COLUMN_OPT_BTN = [COLUMN_SVK]

# Помеха
class Interfer:
    # параметры цели, второе значение, разрешение отправки.
    var get_data: Dictionary = {
    'fpga_ver ':    '',
    'brd_ver':      '',
    'mcu_ver':      '',
    'soc_temp':     '',
    'rf_temp':      '',
    'psu_temp':     '',
    }
    var options: Dictionary = {
    'ispp':         0,
    'krp':          '',
    'powp':         0.0,
    'kni':          0.0,
    'params':       {},
    'get':          [],
    }
    var svk: int = 0
    var row_id: int
    var active_fs: fs.Fs
    
    func _init(data: Dictionary):
        options.merge(data, true)

    func update_row():
        var new_row: Array = []
        new_row.append(str(options['ispp']))
        new_row.append(str(SVK[svk]))
        new_row.append(str(options['krp']))
        new_row.append(str(options['powp']))
        new_row.append(str(options['kni']))
        new_row.append(get_val('freq'))
        new_row.append(get_val('width'))
        return new_row

    func get_val(val):
        if options['params'].has(val) :
            return str(options['params'][val])
        else:
            return ''

    func update_interfer(data: Dictionary):
        options.merge(data, true)


func set_interfer(data):
    if interfers.has(data['ispp']):
        interfers[data['ispp']].update_interfer(data)
        var new_row = interfers[data['ispp']].update_row()
        g_table.set_row_text(interfers[data['ispp']].row_id, new_row)
    else:
        var new_interfer = Interfer.new(data)
        interfers[data['ispp']] = new_interfer
        on_row_add(g_table, interfers[data['ispp']])
    var cmd_state: int = fs.set_fs(interfers[data['ispp']])
    interfers[data['ispp']].svk = cmd_state
    var cell = g_table.get_node2(COLUMN_SVK, interfers[data['ispp']].row_id)
    cell.select(cmd_state)


func init_table(table: Table, sizes: Array):
    for i_row in table.get_rows_count():
        table.set_nodes_min_size(i_row, sizes)


func init_opt_btns(row : int, table):
    for item in COLUMN_OPT:
        var i_col = item[0]
        var opt_arr = item[1]
        var cell = table.get_node2(i_col, row)
        for opt in opt_arr:
            cell.add_item(opt)
        cell.select(0)


func init_pomehi(table):      # Инициализация вкладки с целями
    g_table = table
    g_table.set_header(TABLE_HEADER_TYPES)
    g_table.set_header_text(TABLE_HEADERS)
    init_table(g_table, TABLE_COLUMN_SIZES)
    g_table.connect('row_pressed', Callable(self, 'on_row_pressed').bind(g_table))


func on_row_add(table, interfer):
    var row = interfer.update_row()
    table.add_row(TABLE_ROW_TYPES)
    table.set_row_text(table.get_rows_count()-1, row)
    table.set_columns_min_size(TABLE_COLUMN_SIZES)
    table.set_node_user_data(0, table.get_rows_count()-1, interfer)
    interfer.row_id = table.get_rows_count()-1
    init_opt_btns(table.get_rows_count()-1, table)
    table.connect_columns(self, 'item_selected', 'on_item_selected', COLUMN_OPT_BTN, [])


func on_item_selected(item_num, node):
    var optbtn_text = node[0].text
    var indexis = g_table.get_key_indexes(node[0].name)
    var row_i = indexis[1]
    var col_i = indexis[0]
    var cell = g_table.get_node2(0,row_i)
    var interfer = g_table.get_node_user_data(0, row_i)
    interfer.svk = item_num


func get_msg7_data():
    var data_to_json : Dictionary
    data_to_json['ts'] = 7
    msg_counter += 1
    data_to_json['ss'] = msg_counter
    data_to_json['sa'] = 1
    data_to_json['msfs'] = []
    data_to_json['msrr'] = []
    data_to_json['ret'] = []
    data_to_json['retss'] = 0
    for key in fs.g_fs_dict:
        var block_fs: fs.Fs = fs.g_fs_dict[key]
        var fs_param: Dictionary = {}
        fs_param['nmfs'] = int(block_fs.nmfs)
        fs_param['isg'] = int(block_fs.isg)
        if block_fs.pow is float:
            fs_param['pow'] = str(block_fs.pow)
        if block_fs.freq is float:
            fs_param['freq'] = str(block_fs.freq)
        if block_fs.width is float:
            fs_param['width'] = str(block_fs.width)
        data_to_json['msfs'].append(fs_param)
    var json = JSON.new().stringify(data_to_json)
    var pac = json.to_utf8_buffer()
    return pac


func on_row_pressed(i_row: int, table):
    pass
    
    
func off_interfer(json_data):
    if not interfers.has(json_data['ispp']): return
    var row_id = interfers[json_data['ispp']].row_id
    if interfers[json_data['ispp']] != null:
        if interfers[json_data['ispp']].active_fs != null:
            fs.fs_off(interfers[json_data['ispp']].active_fs)
    if g_table.get_rows_count() > row_id:
        interfers.erase(json_data['ispp'])
        g_table.remove_row(row_id)
    for i in g_table.get_rows_count():
        var interfer = g_table.get_node_user_data(0, i)
        interfer.row_id = i


func check_interfers_state():
    for interfer in interfers.values():
        if interfer.active_fs != null:
            fs.fs_off(interfer.active_fs)
            interfer.active_fs = null
    for interfer in interfers.values():
        var cmd_state: int = fs.set_fs(interfer)
        interfer.svk = cmd_state
        var cell = g_table.get_node2(COLUMN_SVK, interfer.row_id)
        cell.select(cmd_state)
