let options = {
  diapason_akk: [],
  set_count_sms: "5",
  mailing_media: "0"
};

// получение данных с формы при нажатии
$('#adding_group_start').on('click', async function () {
  if ($('#mailing_media').is(':checked')){
    options.mailing_media = '1';
  } else {
    options.mailing_media = '0';
  }

  clear_log = 0
  let json = JSON.stringify(options);
  let this_class = $(this).hasClass("btn-success");
  if (this_class == true) {
    $(this).removeClass('btn-success');
    $(this).addClass('btn-danger');
    $(this).text("Остановить диалоги");
    $('#log li').remove();
    $('#dialog_all div').remove();
    eel.online_dialog_start(json)();
  } else {
    $(this).removeClass('btn-danger');
    $(this).addClass('btn-success');
    $(this).text("Запустить диалоги");
    eel.stopped('dialog_online') //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
    array_all = []
    $("#num_dialog_users").text(0);
    $('#dialog_all').html('');
  }

});

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

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

Language_Code_List = [['ru', 'Russian'], ['en', 'English'], ['zh-cn', 'Chinese (simplified)'], ['zh-tw', 'Chinese (traditional)'], 
['af', 'Afrikaans'], ['sq', 'Albanian'], ['am', 'Amharic'], ['ar', 'Arabic'], ['hy', 'Armenian'], ['az', 'Azerbaijani'], ['eu', 'Basque'], 
['be', 'Belarusian'], ['bn', 'Bengali'], ['bs', 'Bosnian'], ['bg', 'Bulgarian'], ['ca', 'Catalan'], ['ceb', 'Cebuano'], ['ny', 'Chichewa'], 
['co', 'Corsican'], ['hr', 'Croatian'], ['cs', 'Czech'], ['da', 'Danish'], ['nl', 'Dutch'], ['eo', 'Esperanto'], ['et', 'Estonian'], ['tl', 'Filipino'], 
['fi', 'Finnish'], ['fr', 'French'], ['fy', 'Frisian'], ['gl', 'Galician'], ['ka', 'Georgian'], ['de', 'German'], ['el', 'Greek'], ['gu', 'Gujarati'], 
['ht', 'Haitian Creole'], ['ha', 'Hausa'], ['haw', 'Hawaiian'], ['iw', 'Hebrew'], ['he', 'Hebrew'], ['hi', 'Hindi'], ['hmn', 'Hmong'], ['hu', 'Hungarian'], 
['is', 'Icelandic'], ['ig', 'Igbo'], ['id', 'Indonesian'], ['ga', 'Irish'], ['it', 'Italian'], ['ja', 'Japanese'], ['jw', 'Javanese'], ['kn', 'Kannada'], ['kk', 'Kazakh'], 
['km', 'Khmer'], ['ko', 'Korean'], ['ku', 'Kurdish (Kurmanji)'], ['ky', 'Kyrgyz'], ['lo', 'Lao'], ['la', 'Latin'], ['lv', 'Latvian'], ['lt', 'Lithuanian'], ['lb', 'Luxembourgish'], 
['mk', 'Macedonian'], ['mg', 'Malagasy'], ['ms', 'Malay'], ['ml', 'Malayalam'], ['mt', 'Maltese'], ['mi', 'Maori'], ['mr', 'Marathi'], ['mn', 'Mongolian'], 
['my', 'Myanmar (Burmese)'], ['ne', 'Nepali'], ['no', 'Norwegian'], ['or', 'Odia'], ['ps', 'Pashto'], ['fa', 'Persian'], ['pl', 'Polish'], ['pt', 'Portuguese'], 
['pa', 'Punjabi'], ['ro', 'Romanian'], ['sm', 'Samoan'], ['gd', 'Scots Gaelic'], ['sr', 'Serbian'], ['st', 'Sesotho'], ['sn', 'Shona'], 
['sd', 'Sindhi'], ['si', 'Sinhala'], ['sk', 'Slovak'], ['sl', 'Slovenian'], ['so', 'Somali'], ['es', 'Spanish'], ['su', 'Sundanese'], ['sw', 'Swahili'], 
['sv', 'Swedish'], ['tg', 'Tajik'], ['ta', 'Tamil'], ['te', 'Telugu'], ['th', 'Thai'], ['tr', 'Turkish'], ['uk', 'Ukrainian'], ['ur', 'Urdu'], ['ug', 'Uyghur'], 
['uz', 'Uzbek'], ['vi', 'Vietnamese'], ['cy', 'Welsh'], ['xh', 'Xhosa'], ['yi', 'Yiddish'], ['yo', 'Yoruba'], ['zu', 'Zulu']];
// console.log(Language_Code_List)

$.each(Language_Code_List, function(index, value){
  $('#language_select_1').append(`<option value="${value[0]}">${value[1]}</option>`);
  $('#language_select_2').append(`<option value="${value[0]}">${value[1]}</option>`);
})
let lang_code = ['default_original','default_original']
$("#language_select_1").change(function(){
  lang_code[0] = $( "#language_select_1 option:selected").val();
  console.log(lang_code)
  localStorage.setItem('lang_code_select', lang_code);
});
$("#language_select_2").change(function(){
  lang_code[1] = $( "#language_select_2 option:selected").val();
  console.log(lang_code)
  localStorage.setItem('lang_code_select', lang_code);
});

lang_code_history = localStorage.getItem('lang_code_select');
if (lang_code_history != null){
  lang_code = lang_code_history.split(",");
  $('#language_select_1').find("option[value='" + lang_code[0] + "']").attr('selected','selected');
  $('#language_select_2').find("option[value='" + lang_code[1] + "']").attr('selected','selected');
}



let array_all = []
let count_dialog_all = 0
eel.expose(set_dialog);
function set_dialog(array) {
  $('#dialog_all').html('');
  $('#vip_dialog').html('');
  // $('#dialog_all').html('<div id="vip_dialog" class="d-none" style="width: 100%;"></div>');
  array_all = $.merge(array_all, array);
  array_all.sort((a, b) => new Date(b["date"]) - new Date(a["date"]));
  console.log("сортировка по убыванию даты");

  $.each(array_all, function (index, value) {
    let info_vip_status = localStorage.getItem(value["info"]);
    html = `<div class="card_dialog col-lg-12 mb-2" info="${value["info"]}">
            <div class="card bg-primary text-white">
            <div class="card-body notranslate" style="padding: 0.5rem;">
              <div class="d-flex justify-content-between">${value["phone"]}</div>
              <div class="text-white-50 small message_dialog notranslate">${value["message"]}</div>
              <div class="small date_dialog" style="text-align: right; notranslate">${value["date"]}</div>
            </div>
            </div>
          </div>`;

    if (info_vip_status == 1) {
      $("#vip_dialog").append(html);
    } else {
      $("#dialog_all").append(html);
    }
    // console.log(info_vip_status)
  });
  count_dialog_all = array_all.length
  $("#num_dialog_users").text(count_dialog_all);
}


eel.expose(set_new_dialog);
function set_new_dialog(value) {
  html = `<div class="card_dialog col-lg-12 mb-2" info="${value["info"]}">
          <div class="card bg-primary text-white">
          <div class="card-body notranslate" style="padding: 0.5rem;">
            <div class="d-flex justify-content-between">${value["phone"]}</div>
            <div class="text-white-50 small message_dialog notranslate">${value["message"]}</div>
            <div class="small date_dialog" style="text-align: right; notranslate">${value["date"]}</div>
          </div>
          </div>
        </div>`;
  $("#dialog_all").append(html);
}



eel.expose(message_read_event);
function message_read_event(value) {
  // html = `<div class="mb-2" info="${value["info"]}">
  //           <div class="d-flex justify-content-center">Прочитано клиентом<i class="fas fa-check-double ml-1 pt-1 text-success"></i></div>
  //       </div>`;
  // $("#dialog").append(html);
  // $('#dialog').scrollTop($('#dialog')[0].scrollHeight);

  $('.fa-eye-slash').each(function() {
    $(this).removeClass('fa-eye-slash text-danger').addClass('fa-check-double text-success');
  });
}



// let username_list = localStorage.getItem('login_chat');

$(document).on('click', '#favorites_deal', function () {
  $("#dialog_all").addClass('d-none');
  $("#vip_dialog").removeClass('d-none');
})

$(document).on('click', '#all_deal', function () {
  $("#vip_dialog").addClass('d-none');
  $("#dialog_all").removeClass('d-none');
})

let temp_info_dialog = ''

$(document).on('click', '.card_dialog', function () {
  let info = $(this).attr("info");
  $("#dialog").attr("dialog_info", info);
  eel.get_dialog(info, lang_code)();
  temp_info_dialog = info
  $(this).children("div").removeClass('bg-success');
  $(this).children("div").addClass('bg-primary');
})

$('#save_dialog_favorit').click(function () {
  let info_vip_status = localStorage.getItem(temp_info_dialog);
  if (info_vip_status == 1) {
    localStorage.setItem(temp_info_dialog, 0);
    $("#dialog_all").append($("div").find(`[info='${temp_info_dialog}']`));
    success('Диалог удален из избранных!')
  } else {
    localStorage.setItem(temp_info_dialog, 1);
    $("#vip_dialog").append($("div").find(`[info='${temp_info_dialog}']`));
    success('Диалог добавлен в избранные!')
  }
});

$('#username_btn').click(function () {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($('#dialog_username').text()).select();
  document.execCommand("copy");
  $temp.remove();
  success('Логин скопирован!')
});

$('#delete_dialog_now').click(function () {
  $("#dialog").html('');
  $("div").find(`[info='${temp_info_dialog}']`).remove();
  eel.delete_dialog(temp_info_dialog)();
  count_dialog_all = count_dialog_all - 1
  $("#num_dialog_users").text(count_dialog_all);
  success('Диалог удален!')
});


eel.expose(new_message_event);
function new_message_event(message, info, date) {
  $("div").find(`[info='${info}']`).children("div").removeClass('bg-primary');
  $("div").find(`[info='${info}']`).children("div").addClass('bg-success');
  $("div").find(`[info='${info}'] >>> .message_dialog`).text(message)
  $("div").find(`[info='${info}'] >>> .date_dialog`).text(date)
  let info_vip_status = localStorage.getItem(info);
  if (info_vip_status == 1) {
    $("#vip_dialog").prepend($("div").find(`[info='${info}']`));
  } else {
    $("#dialog_all").prepend($("div").find(`[info='${info}']`));
  }
  // $( "#dialog_all" ).prepend( $("div").find(`[info='${info}']`) );
  // $( "#vip_dialog" ).prepend( $("div").find(`[info='${info}']`) );
}
//   $(".card_dialog").prepend($("div").find(`[info='249916664444|1034735579']`));

//   $("div").find(`[info='249916664444|1034735579']`).prev().before( $("#dialog") );

// $( "#dialog_all" ).prepend( $("div").find(`[info='249926438324|1043195678']`) );

eel.expose(print_dialog);
function print_dialog(html, frend_username) {
  $("#dialog").html(html);
  $('#dialog').scrollTop($('#dialog')[0].scrollHeight);
  $("#dialog_username").text(frend_username);
}

// onkeypress="handleKeyPress(event)"
// function handleKeyPress(e){
//   var key=e.keyCode || e.which;
//    if (key === 13){ // Клавиша Enter
//     let dialog_info = $("#dialog").attr("dialog_info");
//     let text = $('#massage_for_send').val()
//     $('#massage_for_send').val('');
//     eel.send_massage(dialog_info, text, lang_code)();
//   }
// }
 

$('#send_massage_chat').on('click', async function () {
  let dialog_info = $("#dialog").attr("dialog_info");
  let text = $('#massage_for_send').val()
  $('#massage_for_send').val('');
  eel.send_massage(dialog_info, text, lang_code)();
})


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

//         eel.set_count('json')();
//     });

$('#set_sleep_inviting').on('click', async function () {
  $('#set_sleep_modal').modal('hide');
  let count_sms = $('#set_count_sms').val();
  if (count_sms !== "") {
    options.set_count_sms = $('#set_count_sms').val();
  } else {
    options.set_count_sms = "5";
  }
});

eel.expose(set_finished_btn);
function set_finished_btn() {
  $('#adding_group_start').removeClass('btn-danger');
  $('#adding_group_start').addClass('btn-success');
  $('#adding_group_start').text("Запустить добавление");
}



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


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






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

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