extends Node

const btn_txr0: Texture2D = preload('res://green.png')
const btn_txr1: Texture2D = preload('res://grey.png')
const btn_txr2: Texture2D = preload('res://blue.png')
const btn_txr3: Texture2D = preload('res://red.png')

const BANDS: Array = [[400, 1200],
                     [1200, 2000],
                     [2000, 2800],
                     [2800, 3600],
                     [3600, 4400],
                     [4400, 5200],
                     [5200, 6000]
                    ]
const SECTORS: Array = [[314.5, 44.5],
                     [44.5, 134.5],
                     [134.5, 224.5],
                     [224.5, 314.5]
                    ]
const LBLS_SEC: Array = ['315° ... 44°', '45° ... 134°', '135° ... 224°', '225° ... 314°']
const LBLS_LIT: Array = ['1К', '2Н', '3Н', '4В', '5В', '6К', '7К']
const LBLS_PARAM: Array = [
    'Номер модуля ФС:           ',
    'Номер сектора:             ',
    'Номер литеры:              ',
    'Мощность излучения:        ',
    'Частота:                   ',
    'Ширина полосы:             ',
    'Индекс назначенной помехи: ',
    'Исправность модуля ФС:     ',
    ]
const OPT_BTN_TEXT: Array = ['не исправно', 'исправно', 'не определено']
# [номер сектора, номер литеры, номер ФС, координата x, координата y]
const FS_PARAM = [
    [1, 1, 17, 0, 0],
    [1, 2, 19, 50, 0],
    [1, 3, 18, 100, 0],
    [1, 4, 20, 150, 0],
    [1, 5, 21, 200, 0],
    [1, 6, 22, 250, 0],
    [1, 7, 31, 300, 0],
    [2, 1, 33, 0, 50],
    [2, 2, 34, 50, 50],
    [2, 3, 35, 100, 50],
    [2, 4, 36, 150, 50],
    [2, 5, 37, 200, 50],
    [2, 6, 38, 250, 50],
    [2, 7, 47, 300, 50],
    [3, 1, 49, 0, 100],
    [3, 2, 51, 50, 100],
    [3, 3, 50, 100, 100],
    [3, 4, 52, 150, 100],
    [3, 5, 53, 200, 100],
    [3, 6, 54, 250, 100],
    [3, 7, 63, 300, 100],
    [4, 1, 65, 0, 150],
    [4, 2, 66, 50, 150],
    [4, 3, 67, 100, 150],
    [4, 4, 68, 150, 150],
    [4, 5, 69, 200, 150],
    [4, 6, 70, 250, 150],
    [4, 7, 87, 300, 150],
]
const MSG8_DATA = [
    ['roll','Крен корабля, градусы:'],
    ['trim','Дифферент корабля, градусы:'],
    ['year','Корабельное время, год:'],
    ['month','Корабельное время, месяц:'],
    ['day','Корабельное время, день:'],
    ['hour','Корабельное время, час:'],
    ['minute','Корабельное время, минуты:'],
    ['second','Корабельное время, секунды:'],
    ['long','Долгота, градусы:'],
    ['lat','Широта, градусы:'],
    ['course','Курс корабля, градусы:'],
    ['speed','Скорость корабля, узлы:'],
]

var lbls_param_val: Array = []
var g_opt_btn: OptionButton = OptionButton.new()
var g_fs_dict: Dictionary = {}
var g_active_fs: Fs
var g_fs_rect: ReferenceRect
var g_msg8_data: Dictionary = {}

var x0 = 875                       # x координата первой кнопки модуля ФС
var y0 = 40                        # y координата первой кнопки модуля ФС

# Called when the node enters the scene tree for the first time.
class Fs:
    var nmfs: int
    var btn: TextureButton
    var isg: int
    var pow
    var freq
    var width
    var sector: int
    var litera: int
    var interfer = null
    
    func _init(sec, lit, id):
        nmfs = id
        litera = lit
        sector = sec
        isg = 1
    
    func fs_off():
        freq = ''
        pow = ''
        width = ''
        interfer = null
        if isg == 0:
            btn.set_texture_normal(btn_txr3)
        elif isg == 1:
            btn.set_texture_normal(btn_txr0)
        elif isg == 2:
            btn.set_texture_normal(btn_txr1)
        
        
func init_lbls(tab, x0, y0):
    for i in range(len(LBLS_SEC)):
        var lbl_sec = Label.new()
        tab.add_child(lbl_sec)
        lbl_sec.position = Vector2(x0 - 100, y0 - 5 + i * 50)
        lbl_sec.text = LBLS_SEC[i]
    
    for i in range(len(LBLS_LIT)):
        var lbl_lit = Label.new()
        tab.add_child(lbl_lit)
        lbl_lit.position = Vector2(x0 -5 + i * 50, y0 - 25)
        lbl_lit.text = LBLS_LIT[i]
        
    for i in range(len(LBLS_PARAM)):
        var lbl_param = Label.new()
        tab.add_child(lbl_param)
        lbl_param.position = Vector2(x0 + 350, y0 - 25 + i * 25)
        lbl_param.text = LBLS_PARAM[i]
    
    for i in range(len(LBLS_PARAM) - 1):
        var lbl_param_val = Label.new()
        tab.add_child(lbl_param_val)
        lbls_param_val.append(lbl_param_val)
        lbl_param_val.position = Vector2(x0 + 600, y0 - 25 + i * 25)
        lbl_param_val.text = ''
        
    tab.add_child(g_opt_btn)
    g_opt_btn.position = Vector2(x0 + 550, y0 - 5 + 150)
    for opt in OPT_BTN_TEXT:
        g_opt_btn.add_item(opt)
    g_opt_btn.visible = false
    g_opt_btn.connect('item_selected', Callable(self, 'on_item_selected'))

    for i in range(len(MSG8_DATA)):
        var lbl_msg8_head = Label.new()
        tab.add_child(lbl_msg8_head)
        lbl_msg8_head.position = Vector2(x0 + 350, y0 + 200 + i * 25)
        lbl_msg8_head.text = MSG8_DATA[i][1]
        var lbl_msg8 = Label.new()
        tab.add_child(lbl_msg8)
        lbl_msg8.position = Vector2(x0 + 600, y0 +200 + i * 25)
        lbl_msg8.text = ''
        g_msg8_data[MSG8_DATA[i][0]] = lbl_msg8


func init_fs(tab, fs_rect):
    for item in fs.FS_PARAM:
        var block_fs = fs.Fs.new(item[0], item[1], item[2])
        g_fs_dict[item[2]] = block_fs
        var btn = TextureButton.new()
        block_fs.btn = btn
        tab.add_child(btn)
        btn.position = Vector2(x0 + item[3], y0 + item[4])
        btn.size = Vector2(10,10)
        btn.set_texture_normal(btn_txr0)
        btn.connect('pressed', Callable(self, 'on_btn_fs').bind(block_fs))
    fs.init_lbls(tab, x0, y0)
    g_fs_rect = fs_rect
    fs_rect.visible = false


func on_item_selected(item_num):
    g_active_fs.isg = item_num
    if g_active_fs.isg == 0:
        fs_off(g_active_fs)
    elif g_active_fs.isg == 1:
        g_active_fs.btn.set_texture_normal(btn_txr0)
    elif g_active_fs.isg == 2:
        g_active_fs.btn.set_texture_normal(btn_txr1)
    on_btn_fs(g_active_fs)


func fs_off(block_fs):
    block_fs.fs_off()
    if g_active_fs == block_fs:
        on_btn_fs(g_active_fs)


func on_btn_fs(block_fs: Fs):
    g_active_fs = block_fs
    g_opt_btn.visible = true
    lbls_param_val[0].text = str(block_fs.nmfs)
    lbls_param_val[1].text = str(block_fs.sector)
    lbls_param_val[2].text = str(block_fs.litera)
    if block_fs.interfer == null:
        lbls_param_val[3].text = ''
        lbls_param_val[4].text = ''
        lbls_param_val[5].text = ''
        lbls_param_val[6].text = ''
    else:
        lbls_param_val[3].text = str(block_fs.interfer['options']['powp'])
        lbls_param_val[4].text = str(block_fs.interfer.get_val('freq'))
        lbls_param_val[5].text = str(block_fs.interfer.get_val('width'))
        lbls_param_val[6].text = str(block_fs.interfer['options']['ispp'])
    g_opt_btn.select(block_fs.isg)
    g_fs_rect.visible = true
    g_fs_rect.position = Vector2(g_active_fs.btn.position[1] - 1, g_active_fs.btn.position[0] - 1)


func set_fs(interfer: Interfers.Interfer):
    var sec: int
    var lit: int
    var freq = interfer.get_val('freq')
    var width = interfer.get_val('width')
    if (freq == '') or (width == ''):
        fs_of_old(interfer)
        return 2
    for i in range(len(BANDS)):
        if (float(freq) >= BANDS[i][0]) and (float(freq) <= BANDS[i][1]):
            lit = i+1
            
    if (float(interfer.options['kni']) < 0) or (float(interfer.options['kni'] > 360)):
        fs_of_old(interfer)
        return 2
    for i in range(len(SECTORS)):
        if i < 1:
            if (float(interfer.options['kni']) >= SECTORS[i][0]) or (float(interfer.options['kni']) <= SECTORS[i][1]):
                sec = i+1
        else:
            if (float(interfer.options['kni']) >= SECTORS[i][0]) and (float(interfer.options['kni']) <= SECTORS[i][1]):
                sec = i+1
    var fs_arr: Array
    fs_arr = FS_PARAM.filter(func(item): return item[0] == sec)
    fs_arr = fs_arr.filter(func(item): return item[1] == lit)
    if len(fs_arr) > 0:
        var fs_num = fs_arr[0][2]
        if g_fs_dict[fs_num].isg == 1:
            if g_fs_dict[fs_num].interfer == null:
                g_fs_dict[fs_num].interfer = interfer
                if (interfer.active_fs != g_fs_dict[fs_num]) and (interfer.active_fs != null):
                    fs_off(interfer.active_fs)
                interfer.active_fs = g_fs_dict[fs_num]
                g_fs_dict[fs_num].pow = float(interfer.options['powp'])
                g_fs_dict[fs_num].freq = float(freq)
                g_fs_dict[fs_num].width = float(width)
                update_fs(g_fs_dict[fs_num], float(interfer.options['powp']), float(freq), float(width))
                g_fs_dict[fs_num].btn.set_texture_normal(btn_txr2)
                if g_active_fs == g_fs_dict[fs_num]:
                    on_btn_fs(g_active_fs)
                return 1
            elif g_fs_dict[fs_num].interfer == interfer:
                update_fs(g_fs_dict[fs_num], float(interfer.options['powp']), float(freq), float(width))
                if g_active_fs == g_fs_dict[fs_num]:
                    on_btn_fs(g_active_fs)
                return 1
            else:
                fs_of_old(interfer)
                return 3
        else:
            fs_of_old(interfer)
            return 4
    else:
        fs_of_old(interfer)
        return 2


func fs_of_old(interfer):
    if interfer.active_fs != null:
        fs_off(interfer.active_fs)
        interfer.active_fs.btn.set_texture_normal(btn_txr0)


func update_fs(block_fs, pow, freq, width):
    block_fs.pow = pow
    block_fs.freq = freq
    block_fs.width = width


func on_receive_msg8(data):
    for key in data:
        if g_msg8_data.has(key):
            g_msg8_data[key].text = str(data[key])
    pass


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    pass

