let options = {
    chats: [],
    diapason_akk: [],
    type_pars: 'username_pars',
    type_time: 'day',
    type_lang: 'lang_en',
    type_gender: 'gender_all',
    time_pars: [0,20],
    what_pars: [],
    what_status_pars: [],
    status_agressive: 0
};

$('#parser_start').on('click', async function () {
    //{"chats":["@dfgggh",http....","t.me..."],"online":[0,48],"type":["admin","bots","alluser"]}
    //Получение данных из textarea
    options.chats = [];
    let lines = $('#username_textarea_parser').val().split(/\n/);
    //let texts = [];
    for (var i = 0; i < lines.length; i++) {
        if (/\S/.test(lines[i])) {
            options.chats.push($.trim(lines[i]));
        }
    }
    options.what_pars = [];
    // Получение данных типа пользователей
    if ($('#control_admin').is(':checked')) {
        options.what_pars.push("admins");
    } else { }
    if ($('#control_user').is(':checked')) {
        options.what_pars.push("users");
    } else { }

    options.what_status_pars = [];
    //Получение данных типа пользователей
    if ($('#UserStatusOnline').is(':checked')) {
        options.what_status_pars.push("UserStatusOnline");
    } else { }
    if ($('#UserStatusLastMonth').is(':checked')) {
        options.what_status_pars.push("UserStatusLastMonth");
    } else { }
    if ($('#UserStatusLastWeek').is(':checked')) {
        options.what_status_pars.push("UserStatusLastWeek");
    } else { }
    if ($('#UserStatusRecently').is(':checked')) {
        options.what_status_pars.push("UserStatusRecently");
    } else { }
    if ($('#UserStatusEmpty').is(':checked')) {
        options.what_status_pars.push("UserStatusEmpty");
    } else { }
    if ($('#UserStatusAntiBot').is(':checked')) {
        options.what_status_pars.push("UserStatusAntiBot");
    } else { }
    if ($('#UserStatusAll').is(':checked')) {
        options.what_status_pars.push("UserStatusAll");
    } else { }
    if ($('#UserStatusPremium').is(':checked')) {
        options.what_status_pars.push("UserStatusPremium");
        $('#parser_save_premium').removeClass('d-none');
    } else { }
    // =========================================
    if ($('#id_pars').is(':checked')) {
        options.type_pars = 'id_pars';
    } 
    if ($('#id_pars_user').is(':checked')) {
        options.type_pars = 'id_pars_user';
    } 
    if ($('#username_pars').is(':checked')) {
        options.type_pars = 'username_pars';
    } 
    if ($('#phones_pars').is(':checked')) {
        options.type_pars = 'phones';
    } 
    // =========================================
    if ($('#lang_ru').is(':checked')) {
        options.type_lang = 'lang_ru';
    } 
    if ($('#lang_en').is(':checked')) {
        options.type_lang = 'lang_en';
    } 
    if ($('#lang_max').is(':checked')) {
        options.type_lang = 'lang_max';
    } 
    if ($('#lang_mix').is(':checked')) {
        options.type_lang = 'lang_mix';
    } 
    // =========================================
    if ($('#gender_men').is(':checked')) {
        options.type_gender = 'gender_men';
    } 
    if ($('#gender_women').is(':checked')) {
        options.type_gender = 'gender_women';
    } 
    if ($('#gender_all').is(':checked')) {
        options.type_gender = 'gender_all';
    } 
    if ($('#gender_nodetect').is(':checked')) {
        options.type_gender = 'gender_nodetect';
    } 
    // =========================================
    if ($('#status_agressive').is(':checked')){
        options.status_agressive = 1;
    } else {
        options.status_agressive = 0;
    }


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

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

});

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

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

$('#type_time').on('click', function(){
    let this_mode = $(this).attr('type_time');
    if(this_mode == 'hours'){
        $(this).text("дней");
        $(this).attr('type_time','day');
        options.type_time = 'day'
    } else {
        $(this).text("часов");
        $(this).attr('type_time','hours');
        options.type_time = 'hours'
    }
});

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);
function set_number(number) {
    $("#username_num").removeClass('d-none');
    $("#username_num").text(number);// Вывод количества собраных username
}

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

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

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

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



$('#search_name_chat').on('click', async function () {
    $("#username_textarea_parser").val('get_name=Товарный Чат');
});

$('#search_id_chat').on('click', async function () {
    $("#username_textarea_parser").val('get_id=-1001351418281');
});

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