let options = {
    username: [],
    num_subscr: 30,
    subscr_mode: 0,
    a_wait_of_mailing: 1,
    capcha_mode: 0,
    time_sleep: [4,6],
    time_in_sleep: [5,10],
    diapason_akk: [],
    view_mode: 0,
    num_view: [2,5]

};

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

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

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

    if ($('#subscription_mode').is(':checked')){
        options.subscr_mode = 1;
    } else {
        options.subscr_mode = 0;
    }

    if ($('#view_mode').is(':checked')){
        options.view_mode = 1;
        options.num_view[0] = $('#num_view_from').val();
        options.num_view[1] = $('#num_view_before').val();
    } else {
        options.view_mode = 0;
    }

    if ($('#subscription_mode_wait').is(':checked')){
        options.a_wait_of_mailing = 1;
    } else {
        options.a_wait_of_mailing = 0;
    }

    if ($('#capcha_mode').is(':checked')){
        options.capcha_mode = 1;
    } else {
        options.capcha_mode = 0;
    }

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

});

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

$('#subscription_mode').on('click', function () {
    if ($('#subscription_mode').is(':checked')){
        $('.num_subscriptions_input').removeClass('d-none');
    } else {
        $('.num_subscriptions_input').addClass('d-none');
    }
})

$('#view_mode').on('click', function () {
    if ($('#view_mode').is(':checked')){
        $('.num_view_input').removeClass('d-none');
    } else {
        $('.num_view_input').addClass('d-none');
    }
})

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

eel.expose(success_count);
function success_count(num) {
  $("#num_send_user").text(num); 
}

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(dell_elem);
function dell_elem(elem) {
  var text = $('#get_username_channel').val();
//   console.log(text)
  text = text.replace(elem, '');
  $('#get_username_channel').val(text.trim());
  save_login_chat_history();
  get_num_user_list();
};

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

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

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