let options = {
    diapason_akk: [],
    time_start: [2,5],
    time_bot: [2,5],
    phrases_main: [],
    phrases_toknow: [],
    phrases_usuallyuse: [],
    type_name: 'name_current',
    type_cause: 'cause_error',
    browser_automation: 'web_no',
    use_proxy_list: 1,
    proxy_list: [],
    rucaptcha_key: ''
};

$('#activity_start').on('click', async function () {

    let keystr = $('#rucaptcha_key').val().trim();
    if (keystr === '') {
        error('Поле ключа ruCaptcha не может быть пустым!');
        return
    } else {
        options.rucaptcha_key = keystr;
    }


    if ($('#use_proxy_list').is(':checked')) {
        options.use_proxy_list = 1
    } else {
        options.use_proxy_list = 0
    }
    options.proxy_list = [];
    let proxys = $('#proxy_list').val().split(/\n/);
    for (var i = 0; i < proxys.length; i++) {
      if (/\S/.test(proxys[i])) {
        options.proxy_list.push($.trim(proxys[i]));
      }
    }

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

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

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

    if ($('#name_ru').is(':checked')) {
        options.type_name = 'name_ru';
    } 
    if ($('#name_en').is(':checked')) {
        options.type_name = 'name_en';
    } 
    if ($('#name_current').is(':checked')) {
        options.type_name = 'name_current';
    } 


    if ($('#cause_error').is(':checked')) {
        options.type_cause = 'cause_error';
    } 
    if ($('#cause_hack').is(':checked')) {
        options.type_cause = 'cause_hack';
    } 
    if ($('#cause_mix').is(':checked')) {
        options.type_cause = 'cause_mix';
    } 

    if ($('#web_yes').is(':checked')) {
        options.browser_automation = 'web_yes';
    } 
    if ($('#web_no').is(':checked')) {
        options.browser_automation = 'web_no';
    } 

    let time_start_from = $('#time_start_from').val();
    let time_start_before = $('#time_start_before').val();
    if(parseInt(time_start_from) >= parseInt(time_start_before)){
        error('Значение времени "до" не может быть меньше!')
        return
    } else {
        options.time_start[0] = time_start_from;
        options.time_start[1] = time_start_before;
    }

    let time_bot_from = $('#time_bot_from').val();
    let time_bot_before = $('#time_bot_before').val();
    if(parseInt(time_bot_from) >= parseInt(time_bot_before)){
        error('Значение времени "до" не может быть меньше!')
        return
    } else {
        options.time_bot[0] = time_bot_from;
        options.time_bot[1] = time_bot_before;
    }
    
  
    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("Остановить");
        $('#log li').remove();
        await eel.removing_freeze(json)();
    } else {
        $(this).removeClass('btn-danger');
        $(this).addClass('btn-success');
        $(this).text("Запустить");
        eel.stopped('removing_freeze') //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
    }

});

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

// function get_num_user_list(){
//     let lines = $('#username_textarea_phrases').val().split(/\n/).length;
//     $("#num_textarea_phrases").text(lines);
// }

$('#save_phrases').on('click', async function () {
    save_login_history();
    // get_num_user_list();
    success('Настройки сохранены!');
})

// $('#username_textarea_phrases').bind('input', function(){
//     get_num_user_list();
// });
let input_api_key = localStorage.getItem('input_api_key');
$('#rucaptcha_key').val(input_api_key)

function save_login_history(){
    let lines = $('#username_textarea_main').val()
    let lines2 = $('#username_textarea_toknow').val()
    let lines3 = $('#username_textarea_usuallyuse').val()
    let proxy_list = $('#proxy_list').val()
    let rucaptcha_key = $('#rucaptcha_key').val()
    localStorage.setItem('textarea_phrases_main', lines);
    localStorage.setItem('textarea_phrases_toknow', lines2);
    localStorage.setItem('textarea_phrases_usuallyuse', lines3);
    localStorage.setItem('textarea_proxy', proxy_list);
    localStorage.setItem('input_api_key', rucaptcha_key);
}

$('#get_phrases_history').on('click', function(){
    let textarea_phrases_main = localStorage.getItem('textarea_phrases_main');
    let textarea_phrases_toknow = localStorage.getItem('textarea_phrases_toknow');
    let textarea_phrases_usuallyuse = localStorage.getItem('textarea_phrases_usuallyuse');
    let textarea_proxy = localStorage.getItem('textarea_proxy');
    let input_api_key = localStorage.getItem('input_api_key');
    $('#username_textarea_main').val(textarea_phrases_main)
    $('#username_textarea_toknow').val(textarea_phrases_toknow)
    $('#username_textarea_usuallyuse').val(textarea_phrases_usuallyuse)
    $('#proxy_list').val(textarea_proxy)
    $('#rucaptcha_key').val(input_api_key)
    
    get_num_user_list();
  });

eel.expose(set_finished_btn);
function set_finished_btn(){
    $('#activity_start').removeClass('btn-danger');
    $('#activity_start').addClass('btn-success');
    $('#activity_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);
}



$('#use_proxy_list').change(function () {
    if ($(this).is(':checked')) {
    $('#proxy_textarea').removeClass('d-none');
    } else {
    $('#proxy_textarea').addClass('d-none');
    }
});



$('#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
    })
}