extends Button

var base_style: StyleBoxFlat
var tween: Tween
var pulsing: bool = false
var original_text: String
var flag_control_is_over: bool = false


func _ready():
    original_text = text
    _setup_styles()
    _setup_signals()


func _setup_styles() -> void:
    if get('theme_override_styles/disabled') == null:
        base_style = StyleBoxFlat.new()
        base_style.border_color = Color(1.0, 0.5, 0.0)
        base_style.border_width_top = 4
        base_style.border_width_bottom = 4
        base_style.border_width_left = 4
        base_style.border_width_right = 4
        base_style.bg_color = Color(0.2, 0.2, 0.2)
        set('theme_override_styles/disabled', base_style)
    else:
        base_style = get('theme_override_styles/disabled')
    set('theme_override_colors/font_disabled_color', Color(1.0, 1.0, 1.0))


func _setup_signals() -> void:
    connect('pressed', Callable(self, '_on_pressed'))
    var signals_to_connect := ['режим_работа', 'режим_журнал', 'режим_эмс', 'режим_настройки', 'режим_контроль']
    for signal_name in signals_to_connect:
        signaller.connect(signal_name, Callable(self, '_on_status_change'))


func _on_pressed():
    disabled = true
    text = 'Контроль выполняется ...'
    flag_control_is_over = false
    _start_pulse()


func _start_pulse():
    if pulsing:
        return
    pulsing = true
    if not tween:
        tween = create_tween()
    tween.set_loops()
    var color1 = Color(1.0, 0.5, 0.0) # оранжевый
    var color2 = Color(0.4, 0.4, 0.4) # серый
    tween.tween_property(base_style, 'border_color', color2, 0.5).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
    tween.tween_property(base_style, 'border_color', color1, 0.5).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)


func _stop_pulse():
    if tween:
        tween.kill()
        tween = null
    base_style.border_color = Color(1.0, 0.5, 0.0)
    pulsing = false
    disabled = false
    text = original_text
    tooltip_text = ''


func _on_status_change():
    if not flag_control_is_over:
        _stop_pulse()


func _on_stop_control():
    var time_dict = Time.get_datetime_dict_from_system()
    text = 'Контроль завершён %02d:%02d/%02d.%02d' % [
        time_dict.hour,
        time_dict.minute,
        time_dict.day,
        time_dict.month ]
    disabled = false
    tooltip_text = 'Нажать для запуска контроля '
    flag_control_is_over = true


func _exit_tree() -> void:
    if tween:
        tween.kill()
        tween = null
