let options = {
    chats: [],
    diapason_akk: [],
    time_pars: [0,30],
    type_time: 'day',
    time_pars_user: [0,20],
    type_gender: 'gender_all',
    what_status_pars: []
};

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

    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;
    }

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

    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';
    } 

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

    clear_log = 0
    counter_send = 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();
        $("#num_send_parser").text(0);
        save_login_chat_history();
        await eel.username_check(json)();
    } else {
        $(this).removeClass('btn-danger');
        $(this).addClass('btn-success');
        $(this).text("Запустить");
        eel.stopped('username_check') //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
        stoper_sender()
    }

});

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

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

$('#get_username_channel').bind('input', function(){
    get_num_user_list();
});

let mass_username = []

function stoper_sender() {
  username_list_new = []
  $.each(options.chats, function(index, value){
    element = $.inArray(value, mass_username)
    if(element == -1){
      username_list_new.push(value)
    }
  })
  $('#get_username_channel').val(username_list_new.join("\n"));
  save_login_chat_history();
  get_num_user_list();
  success('Логины сохранены!');
}

let counter_send = 0
eel.expose(dell_elem);
function dell_elem(elem) {
  $("#num_send_parser").text(++counter_send);
  mass_username.push(elem)
}

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

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

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

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);
}

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


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

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

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

function success(massege){
    const Toast = Swal.mixin({
        toast: true,
        position: 'bottom-end',
        showConfirmButton: false,
        timer: 2000,
        timerProgressBar: true,
    });
  
    Toast.fire({
        icon: 'success',
        title: massege
    });
}