let mode = 'placeMarker';
let markers = [];
let selection = null;
let coordinates = [];
function get_radius(){
    let radius = Number($('#radius_tg').val())
    // console.log(radius)
    if (radius == 0 || radius <= 10){
        return 50
    } else {
        return Number(radius)
    }
}
function initGoogleMap(){
    // let radius_circles = Number($('#radius_tg').val());
    // console.log('sadas')
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    };

    Number.prototype.toDeg = function() {
        return this * 180 / Math.PI;
    };

    let moveTowards = function(from, to, distance) {
        let lat1 = from.lat.toRad();
        let lon1 = from.lng.toRad();
        let lat2 = to.lat.toRad();
        let lon2 = to.lng.toRad();
        let dLon = (to.lng - from.lng).toRad();

        // Find the bearing from this direction to the next.
        let brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
            Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) *
            Math.cos(dLon));

        let angDist = distance / 6371000;  // Earth's radius.

        // Calculate the destination direction, given the source and bearing.
        lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) +
            Math.cos(lat1) * Math.sin(angDist) *
            Math.cos(brng));

        lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
            Math.cos(lat1),
            Math.cos(angDist) - Math.sin(lat1) *
            Math.sin(lat2));

        if (isNaN(lat2) || isNaN(lon2)) return null;

        return {lat: lat2.toDeg(), lng: lon2.toDeg()};
    };


    let map = new google.maps.Map(document.getElementById("map"), {
        zoom: 5,
        center: { lat: 50.45000109544508, lng: 30.524086621739627 },
        mapTypeControl: false,
        streetViewControl: false,

    });
    google.maps.event.addDomListener(map, 'click', e => {
        if(mode === 'placeMarker') {
            let marker = new google.maps.Circle({
                strokeColor: "#6777EF",
                strokeOpacity: 0.9,
                strokeWeight: 2,
                fillColor: "#6777EF",
                fillOpacity: 0.25,
                center: e.latLng,
                map: map,
                radius: get_radius(),
            });
            markers.push(marker);
            google.maps.event.addDomListener(marker, 'click', e => {
                let latLng = marker.center.toJSON();
                for(let i in coordinates){
                    if(coordinates[i].lat === latLng.lat && coordinates[i].lng === latLng.lng){
                        coordinates.splice(i,1);
                    }
                }
                marker.setMap(null);
                print_coords(coordinates)
            });
            coordinates.push(e.latLng.toJSON());
            map.panTo(e.latLng);
            print_coords(coordinates)
            // console.log(coordinates);
        } else if(mode === 'zoneSelection'){
            if(selection) selection.setMap(null);
            selection = new google.maps.Rectangle({
                strokeColor: '#6777EF',

                fillColor: "#6777EF",
                fillOpacity: 0.25,
                bounds: {
                    north: e.latLng.lat() + 0.00300,
                    south: e.latLng.lat() - 0.00300,
                    east: e.latLng.lng() + 0.00300,
                    west: e.latLng.lng() - 0.00300
                },
                editable: true,
                draggable: true,
            });
            selection.setMap(map);
            let getSelectionCoordinates = () => {

                let distance = get_radius();

                let ne = selection.getBounds().getNorthEast().toJSON();
                let sw = selection.getBounds().getSouthWest().toJSON();
                let nw = {lat: ne.lat, lng: sw.lng};
                let se = {lat: sw.lat, lng: ne.lng};

                let verticalPoint = nw;
                let horizontalPoint = nw;

                let hIndex = 0;
                let vIndex = 0;
                for(let m in markers){
                    markers[m].setMap(null);
                }
                markers = [];
                coordinates = [];

                while(verticalPoint.lat > sw.lat){
                    if(vIndex > 100) break;
                    verticalPoint = moveTowards(verticalPoint, sw, vIndex === 0 ? distance : distance * 2);
                    horizontalPoint = {lat: verticalPoint.lat, lng: verticalPoint.lng};
                    hIndex = 0;
                    while(horizontalPoint.lng < ne.lng){
                        if(hIndex > 100) break;
                        horizontalPoint = moveTowards(horizontalPoint, {lat: verticalPoint.lat, lng: ne.lng}, hIndex === 0 ? distance : distance * 2);
                        if(horizontalPoint.lat > sw.lat && horizontalPoint.lng < ne.lng){
                            // let marker = new google.maps.Circle({
                            //     strokeColor: '#6777EF',
                            //     strokeOpacity: 0.9,
                            //     strokeWeight: 2,
                            //     fillColor: '#6777EF',
                            //     fillOpacity: 0.25,
                            //     center: horizontalPoint,
                            //     map: map,
                            //     radius: get_radius(),
                            // });
                            // marker.setMap(map);
                            // markers.push(marker);
                            coordinates.push(horizontalPoint);
                        }
                        hIndex++;
                    }
                    vIndex++;
                }
                print_coords(coordinates)
                
            };
            getSelectionCoordinates();
            google.maps.event.addDomListener(selection, 'bounds_changed', getSelectionCoordinates);
        }
    });
}

function clear_map(){
        
    if(selection){
        selection.setMap(null);
        selection = null;
    }
    for(let m in markers){
        markers[m].setMap(null);
    }
    markers = [];
    coordinates = [];
}  

$('#clear_geo').on('click', function () {
    $('#coordinat_list span').remove();
    $('#coordinat_list').append('<span class="badge badge-primary">Выберете область на карте...</span>')
    $('#num_geo').text('0');
    clear_map();
})

$('#type_select_geo').on('click', function () {
    let this_mode = $(this).attr('type_select');
    // console.log(this_mode)
    if(this_mode === 'square'){
        $(this).text("Круги");
        $(this).attr('type_select','circles');
        mode = 'zoneSelection'
    } else {
        $(this).text("Квадрат");
        $(this).attr('type_select','square');
        mode = 'placeMarker'
    }
})

function print_coords(coordinates){
    $('#coordinat_list span').remove();
    $('#num_geo').text(coordinates.length);
    if (coordinates.length == 0){
        $('#coordinat_list').append('<span class="badge badge-primary">Выберете область на карте...</span>')
        return
    }
    for (var i = 0; i < coordinates.length; i++) {
        let lat = String(coordinates[i]['lat']).substring(0, 8)
        let lng = String(coordinates[i]['lng']).substring(0, 8)
        $('#coordinat_list').append('<span class="badge badge-primary ml-1 notranslate">' + lat + ', ' + lng + '</span>');
        // <span class="badge badge-primary">46.485472, 30.725627</span>
    }
}

// -----------------------------------------------------------

let options = {
    coordinates: [],
    diapason_akk: [],
    change_coord: 1,
    radius_tg: 50,
    waiting_time: 3,
    type_gender: 'gender_all',
};

$('#start_geo_parser').on('click', async function () {
    let change_coord = Number($('#change_coord').val());
    if (change_coord !== 0) {
        options.change_coord = change_coord;
    }
    options.radius_tg = get_radius();
    let waiting_time = Number($('#waiting_time').val());
    if (waiting_time !== 0) {
        options.waiting_time = waiting_time;
    }
    options.coordinates = coordinates;

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

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

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

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

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

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

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

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

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

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

// ВСЕ ЧТО КАСАЕТСЯ JS ФАЙЛА
$('#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(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(counter_sess);
function counter_sess(num) {
  $("#counter_sess").text(num);
}