let options = {
  message: "",
  diapason_akk: [],
  username_list: [],
  sleep_send_sms: [1,3],
  answer_sleep_start: [4,8],
  answer_sleep: [2,8],
  delay_mailing: [10,30],
  quantity: "",
  messages_for_answer: "",
  answer_status: "0",
  delay_mailing_status: "0",
  a_wait_of_mailing: "0",
  skip_toomany_limit_mailing: "0",
  delete_sms_yourself: "0",
  count_toomany_limit_mailing: "30",
  link_preview_mailing: true,
  file_list: []
};

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

  // Получение изображения если есть передаем в обьект
  let quantity_max = $('#send_account_full').val();
  if (quantity_max !== "") {
    options.quantity = $('#send_account_full').val();
  } else {
    options.quantity = "50";
  }

  if ($('#delay_mailing').is(':checked')){
    options.delay_mailing_status = '1';
    options.delay_mailing[0] = $('#delay_mailing_hours').val();
    options.delay_mailing[1] = $('#delay_mailing_minute').val();
  } else {
    options.delay_mailing_status = '0';
  }

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

  if ($('#link_preview_mailing').is(':checked')){
    options.link_preview_mailing = false;
  } else {
    options.link_preview_mailing = true;
  }

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

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

  // Получение сообщения
  options.message = $('#text_textarea').val();

  // Получение данных из textarea - @username
  options.username_list = [];
  let lines = $('#username_textarea_send').val().split(/\n/);
  for (var i = 0; i < lines.length; i++) {
    if (/\S/.test(lines[i])) {
      options.username_list.push($.trim(lines[i]));
    }
  }

  // Получение данных из textarea - файлы
  options.file_list = [];
  let lines2 = $('#add_file_textarea').val().split(/\n/);
  for (var i = 0; i < lines2.length; i++) {
    if (/\S/.test(lines2[i])) {
      options.file_list.push($.trim(lines2[i]));
    }
  }

  
  clear_log = 0
  let json = JSON.stringify(options);
  let this_class = $(this).hasClass("btn-success");
  if (this_class == true) {
    if(options.answer_status == '1'){
      let this_class = $('#start_answer').hasClass("d-none");
      if(this_class == false){
        error('Сначала завершите автоответчик!')
        return
      }
      $('#start_answer').removeClass('d-none');
    }
    // =============
    $("#num_send_user").text(0);
    // =============
    $(this).removeClass('btn-success');
    $(this).addClass('btn-danger');
    $(this).text("Остановить рассылку");
    $('#log li').remove();
    $('#log_div li').remove();
    await eel.send_message(json)();
  } else {
    $(this).removeClass('btn-danger');
    $(this).addClass('btn-success');
    $(this).text("Запустить рассылку");
    if(options.answer_status == '1'){
      eel.stopped('spam_answer_event')
    } else { eel.stopped('spam') } //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
    stoper_sender()
  }

});

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

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

  Toast.fire({
      icon: 'success',
      title: massege
  });
}

$('#start_answer').on('click', async function () {
  $('#start_answer').addClass('d-none');
  eel.stopped('answer_sent')
})

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

$('#set_sleep_sending').on('click', async function () {
  $('#set_sleep_modal').modal('hide');
  options.sleep_send_sms[0] = $('#sleep_send_sms_from').val();
  options.sleep_send_sms[1] = $('#sleep_send_sms_before').val();
  options.answer_sleep_start[0] = $('#answer_sleep_start_from').val();
  options.answer_sleep_start[1] = $('#answer_sleep_start_before').val();
  options.answer_sleep[0] = $('#answer_sleep_from').val();
  options.answer_sleep[1] = $('#answer_sleep_before').val();
});

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

$('#select_accounts').on('click', async function () {
  options.diapason_akk = [];
  load_accounts();
});

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

$('#save_massage').on('click', async function () {
  let text = $("#text_textarea").val();
  localStorage.setItem('text_sender', text);
});

$('#get_save_massage').on('click', async function () {
  let text = localStorage.getItem('text_sender');
  $('#text_textarea').val(text)
});

// ========================= Продолжать рассылку при временном ограничении на отправку сообщений? ========================= 
$('#a_wait_of_mailing').on('click', async function () {
  let posting_mode = 0
  if ($('#a_wait_of_mailing').is(':checked')){ posting_mode = 1;} else { posting_mode = 0;}
  localStorage.setItem('posting_mode', posting_mode);
});

a_wait_of_mailing()
function a_wait_of_mailing() {
  let posting_mode = localStorage.getItem('posting_mode');
  if(posting_mode == 1)
    $("#a_wait_of_mailing").prop( 'checked', true )  // checked
  else
    $("#a_wait_of_mailing").prop( 'checked', false )  // unchecked
};
// ==================================================================================

$('#repost_channel').on('click', async function () {
  $("#text_textarea").val('repost@https://t.me/notcoin/733');
});

$('#repost_hidden_channel').on('click', async function () {
  $("#text_textarea").val('repost_hidden@https://t.me/notcoin/733');
});

$('#sendbot_channel').on('click', async function () {
  $("#text_textarea").val('sendbot@PostBot@63cdb7581c7ae');
});

$('#send_no_intersections').on('click', async function () {
  $("#text_textarea").val('no_intersections@10@texts.txt');
});

$('#sendedit_message').on('click', function () {
    $("#text_textarea").val(`text1=[
{Привет|Здравствуйте|Добрый день}
как дела?
]text2=[
рекламный текст
]time=[8-10]
`);
});

// ОБРАБОТЧИК НАЖАТИЯ КАРТИНКА
$('#add_img').on('click', async function () {
  let img_res = await eel.get_image_for_message()();//тут нужно вставить путь на картинку которую выбрал пользователь
  console.log(img_res)
  if (img_res !== "" && img_res !== 0 && img_res != false) {// Демонстрация изображения если есть
    $('#myimage').attr('src', img_res[0]);
    $.each(img_res, function(index, value){
      let text = $("#add_file_textarea").val();
      $('#add_file_textarea').val(text + 'web/' + value + '\n')
    })
    $("#add_file_form").removeClass('d-none');
    // $('#add_file_textarea').val(text + 'web/' + img_res + '\n')
  }
});

$('#select_accounts_apply').on('click', async function () {
  console.log("Нажали")
  $('#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(counter_sess);
function counter_sess(num) {
  $("#counter_sess").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(reload_python);
function reload_python() {
  window.location.reload();
}

$('#save_logins').on('click', async function () {
  save_login_history();
  get_num_user_list();
  success('Логины сохранены!');
})


let mass_username = []

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




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

eel.expose(dell_elem);
function dell_elem(elem) {
  mass_username.push(elem)
};



let answer_num = 2;
$('#answer_sms_add').on('click', async function () {
  multi_dialog = await eel.paid_func('multi_dialog')();
  if(multi_dialog == false){
    error('Модуль не активирован!')
    return
  }
  $('#answer_sms').append('<label class="mt-2 answer_sms_cl">Ответ №' + answer_num++ + '</label>');
  $('#answer_sms').append('<textarea class="form-control answer_sms_text" rows="7">' + '</textarea>');
  $('#answer_sms').append('<input class="input-sm form-control mt-1 answer_sms_key" type="text" placeholder="Ключевое слово для ответа">' + '</input>');
  // <input id="key_answering" type="text" class="input-sm form-control mt-1" placeholder="Ключевое слово"></input>

  $('#answer_sms_dell').removeClass('d-none');
});

function answer_text(){
  let from = 0
  let before  = $('.answer_sms_cl').length
  let mass_text = []
  mass_text.push([$('#text_textarea_answering').val(),$('#key_answering').val()]);
  for (let i = from; i < before; i++) {
    let text = $('.answer_sms_text').eq(i).val();
    let key = $('.answer_sms_key').eq(i).val();
    console.log(text, key)
    mass_text.push([text, key]);
  }
  console.log(before)
  return mass_text
}

// Отложка смс
$('#delay_mailing').on('click', async function () {
  if ($('#delay_mailing').is(':checked')){
    $('#delay_mailing_form').removeClass('d-none');
    var date = new Date();
    $('#delay_mailing_hours').val(date.getHours());
    $('#delay_mailing_minute').val(date.getMinutes());

  } else {
    $('#delay_mailing_form').addClass('d-none');
  }
});

$('#answer_sms_dell').on('click', async function () {
  let count = $("#answer_sms label").last().text().split('№')[1]
  answer_num = Number(count)
  $("#answer_sms label").last().remove();
  $("#answer_sms textarea").last().remove();
  $("#answer_sms input").last().remove();
  if(answer_num == 2){
    $('#answer_sms_dell').addClass('d-none');
  }
});

// Автоответчик
$('#answering_check').on('click', function () {
  let this_class = $('#alerts_color').hasClass("alert-success");
  if (this_class == true) {
    $('#alerts_color').removeClass('alert-success');
    $('#alerts_color').addClass('alert-primary');
    $('#answering_check_text').text("Включить автоответчик во время рассылки?");
    $('#sms_answer_check').addClass('d-none');
    options.answer_status = '0';
    $('#answering_log_block').addClass('d-none');
    $('#log_div').css('height', '571px');
    $('#start_answer').addClass('d-none');
  } else {
    $('#alerts_color').removeClass('alert-primary');
    $('#alerts_color').addClass('alert-success');
    $('#answering_check_text').text("Автоответчик активирован!");
    $('#write_text_answering').modal('show');
    $('#sms_answer_check').removeClass('d-none');
    options.answer_status = '1';
    $('#answering_log_block').removeClass('d-none');
    $('#log_div').css('height', '272px');
  }
});
$('#sms_answer_check').on('click', function () {
  $('#write_text_answering').modal('show');
});
$('#get_text_answering').on('click', function () { 
  // options.messages_for_answer = $('#text_textarea_answering').val();
  options.messages_for_answer = answer_text()
  $('#write_text_answering').modal('hide');
  console.log(options.messages_for_answer);
});
eel.expose(log_answer);
function log_answer(log_line) {
  $('#answering_log').append('<li>' + log_line + '</li>');
  $('#answering_log_div').scrollTop($('#answering_log_div')[0].scrollHeight);
}

function save_login_history() {
  let lines = $('#username_textarea_send').val()
  localStorage.setItem('login_send', lines);
}

$('#get_login_history').on('click', function () {
  let username_list = localStorage.getItem('login_send');
  $('#username_textarea_send').val(username_list)
  get_num_user_list();
});