let options = {
    username_list: [],
    keys: [],
    diapason_akk: [],
    days: 30,
};

$('#search_chat_start').on('click', async function () {
    //{"chats":["@dfgggh",http....","t.me..."],"online":[0,48],"type":["admin","bots","alluser"]}
    //Получение данных из textarea
    options.keys = [];
    let lines = $('#get_key_word').val().split(/\n/);
    //let texts = [];
    for (var i = 0; i < lines.length; i++) {
        if (/\S/.test(lines[i])) {
            options.keys.push($.trim(lines[i]));
        }
    }

    options.username_list = [];
    let lines2 = $('#get_username').val().split(/\n/);
    for (var i = 0; i < lines2.length; i++) {
      if (/\S/.test(lines2[i])) {
        options.username_list.push($.trim(lines2[i]));
      }
    }

    let parsing_depth = Number($('#parsing_depth').val());
    if (parsing_depth !== 0) {
        options.days = parsing_depth;
    }

    clear_log = 0
    let json = JSON.stringify(options);
    //Получили json обьект
    let this_class = $(this).hasClass("btn-success");
    if (this_class == true) {
        $(this).removeClass('btn-success');
        $(this).addClass('btn-danger');
        $(this).text("Остановить");
        $("#username_num").addClass('d-none');
        $("#username_num").text('0');
        $('#log li').remove();
        save_login_chat_history();
        save_key_word_history();
        console.log(json)
        await eel.search_keys_chats(json)();
    } else {
        $(this).removeClass('btn-danger');
        $(this).addClass('btn-success');
        $(this).text("Запустить");
        eel.stopped('search_keys_chats') //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
    }

});

window.addEventListener("beforeunload", function (e) {        
    eel.stopped('search_keys_chats')
});

eel.expose(set_finished_btn);
function set_finished_btn(){
    $('#search_chat_start').removeClass('btn-danger');
    $('#search_chat_start').addClass('btn-success');
    $('#search_chat_start').text("Запустить");
}


let clear_log = 0
eel.expose(log);
function log(log_line) {
  if (clear_log == 250){
    $('#log li:first').remove();
  } else {clear_log = clear_log + 1}
  $('#log').append('<li>' + log_line + '</li>');
  $('#log_div').scrollTop($('#log_div')[0].scrollHeight);
}


eel.expose(set_number_front);
function set_number_front(number) {
    $("#username_num").removeClass('d-none');
    $("#username_num").text(number);// Вывод количества собраных username
}

$('#search_save_username').on('click', function () {
    var link = document.createElement('a');
    link.setAttribute('href', '/uploads/logins_chat_search_keys.txt');
    link.setAttribute('download', 'logins_chat_search_keys.txt');
    link.click();
    return false;
});

function save_login_chat_history(){
    let lines = $('#get_username').val()
    localStorage.setItem('get_login_chat_chat', lines);
}
  
$('#get_login_chat_history').on('click', function(){
    let username_list = localStorage.getItem('get_login_chat_chat');
    $('#get_username').val(username_list)
});

function save_key_word_history(){
    let lines = $('#get_key_word').val()
    localStorage.setItem('get_listener_key_chat', lines);
}
  
$('#get_key_word_history').on('click', function(){
    let username_list = localStorage.getItem('get_listener_key_chat');
    $('#get_key_word').val(username_list)
});



$('#select_accounts').on('click', async function () {
    options.diapason_akk = [];
    load_accounts();
});

$('#select_accounts_apply').on('click', async function () {
    $('#select_accounts_modal').modal('hide');
    let from = 1;
    let before = $('#table_users >tbody >tr').length;
    //Запускаем цикл по всей таблице
    for (let i = from; i <= before; i++) {
        let type_bg = $('#table_users tr').eq(i).attr("class");
        if (type_bg == "bg_selected") {
        //Получаем номер телефона
        phone_user = $('#table_users tr').eq(i).children('#phone').html();
        options.diapason_akk.push(phone_user);
        }
    }
    $("#account_num").removeClass('d-none');
    $("#account_num").text(options.diapason_akk.length);
});

// eel.expose(error);
function error(text) {
    Swal.fire({
        position: 'center',
        icon: 'error',
        title: 'Ошибка',
        text: text,
        showConfirmButton: false,
        timer: 2100
    })
}