let options = {
    phone: [],
    change_account: 20,
    diapason_akk: [],
    type_time: 'day',
    time_pars: [0,20],
    time_sleep: [8,15],
    what_status_pars: []
};

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

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

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


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

    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
    counter_send = 0
    let json = JSON.stringify(options);
    //Получили json обьект
    let this_class = $(this).hasClass("btn-success");
    if (this_class == true) {
        // =============
        counter_send = 0
        $("#num_send_user").text(counter_send);
        // =============
        $(this).removeClass('btn-success');
        $(this).addClass('btn-danger');
        $(this).text("Остановить");
        $("#get_username_num").addClass('d-none');
        $("#get_username_num").text('0');
        $("#get_phone_username_num").addClass('d-none');
        $("#get_phone_username_num").text('0');
        $("#get_phone_num").addClass('d-none');
        $("#get_phone_num").text('0');
        $('#log li').remove();
        save_login_chat_history();
        console.log(json)
        await eel.phone_parser(json)();
    } else {
        $(this).removeClass('btn-danger');
        $(this).addClass('btn-success');
        $(this).text("Запустить");
        eel.stopped('parser_phone') //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
        stoper_sender()
    }

});

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

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

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

$('#save_logins').on('click', async function () {
    save_login_chat_history();
    get_num_user_list();
    success('Номера сохранены!');
})

let mass_username = []

function stoper_sender() {
  username_list_new = []
  console.log(mass_username)
  $.each(options.phone, function(index, value){
    element = $.inArray(value, mass_username)
    if(element == -1){
      username_list_new.push(value)
    }
  })
  $('#username_textarea_parser').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)
//   var text = $('#username_textarea_parser').val();
//   //console.log(text)
//   text = text.replace(elem, '');
//   $('#username_textarea_parser').val(text.trim());
//   save_login_chat_history();
//   //get_num_user_list();
};


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

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

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

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

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

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

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

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


function get_num_user_list(){
    let lines = $('#username_textarea_parser').val().split(/\n/).length;
    $("#num_textarea_user").text(lines);
  }
  $('#username_textarea_parser').bind('input', function(){
    get_num_user_list();
  });

function save_login_chat_history(){
    let lines = $('#username_textarea_parser').val()
    localStorage.setItem('login_phone', lines);
}
  
$('#get_login_chat_history').on('click', function(){
    let username_list = localStorage.getItem('login_phone');
    $('#username_textarea_parser').val(username_list)
    get_num_user_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
    })
}