var live_time, is_live, load_timeout, app_datatable, map, api_url;

function cb (start, end) {
    is_live = live_time.isSame(start);

    if (is_live) {
        $('#reportrange span').html(<?=$this->escapeJs(__('Live Listeners')) ?>);
    } else {
        $('#reportrange span').html(start.format('ll') + ' - ' + end.format('ll'));
    }

    updateListeners(start, end);
}

var updateListeners = function (start, end) {
    clearTimeout(load_timeout);

    var params = {};
    var export_url = api_url + '?format=csv';

    if (!is_live) {
        params.start = start.format('YYYY-MM-DD H:mm:ss');
        params.end = end.format('YYYY-MM-DD H:mm:ss');
        export_url += '&start=' + params.start + '&end=' + params.end;
    }

    $('#btn-export').attr('href', export_url);

    $.getJSON(api_url, params, function (data) {
        app_datatable.listeners = data;
        setMapPoints(data);

        if (is_live) {
            load_timeout = setTimeout(updateListeners, 15 * 1000);
        }
    });
};

function initMap () {
    map = L.map('map', {
        fullscreenControl: true
    }).setView([40, 0], 1);

    L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/' + App.theme + '_all/{z}/{x}/{y}.png', {
        attribution: 'Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL.'
    }).addTo(map);
}

var markers = new Array();

function setMapPoints (points) {
    for (i = 0; i < markers.length; i++) {
        map.removeLayer(markers[i]);
    }
    markers = [];

    if (points.length > 3000) {
        if ($('#map').is(':visible')) {
            notify(<?=$this->escapeJs(__('There are too many data points to map!')) ?>, 'warning');
            $('#map').hide();
        }
    } else {
        $('#map').show();

        $.each(points, function (i, l) {
            if (l.location.status !== 'success')
                return null;

            var marker = new L.marker([l.location.lat, l.location.lon])
                .bindPopup('IP: ' + l.ip + '<br>' +
                    'Country: ' + l.location.country + '<br>' +
                    'Region: ' + l.location.region + '<br>' +
                    'City: ' + l.location.city + '<br>' +
                    'Time connected: ' + l.connected_time + '<br>' +
                    'User Agent: ' + l.user_agent)
                .addTo(map);

            markers.push(marker);
        });
    }
}

$(function () {
    api_url = '<?=$router->named('api:listeners:index', ['station_id' => $station->getId()]) ?>';
    live_time = moment().add(1, 'days');

    $('#reportrange').daterangepicker({
            showDropdowns: true,
            minYear: 2016,
            maxYear: parseInt(moment().format('YYYY'), 10),
            startDate: live_time,
            endDate: live_time,
            opens: 'left',
            timePicker: true,
            ranges: {
                <?=$this->escapeJs(__('Live Listeners')) ?>:
                    [live_time, live_time],
                <?=$this->escapeJs(__('Today')) ?>:
                    [moment().startOf('day'), moment().endOf('day')],
                <?=$this->escapeJs(__('Yesterday')) ?>:
                    [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                <?=$this->escapeJs(__('Last 7 Days')) ?>:
                    [moment().subtract(6, 'days').startOf('day'), moment().endOf('day')],
                <?=$this->escapeJs(__('Last 30 Days')) ?>:
                    [moment().subtract(29, 'days').startOf('day'), moment().endOf('day')],
                <?=$this->escapeJs(__('This Month')) ?>:
                    [moment().startOf('month').startOf('day'), moment().endOf('month').endOf('day')],
                <?=$this->escapeJs(__('Last Month')) ?>:
                    [moment().subtract(1, 'month').startOf('month').startOf('day'), moment().subtract(1, 'month').endOf('month').endOf('day')]
            }
        },
        cb
    )
    ;

    app_datatable = new Vue({
        el: '#app-datatable',
        data: {
            listeners: []
        },
        computed: {
            total_listener_hours: function () {
                var tlh_seconds = 0;
                this.listeners.forEach(function (listener) {
                    tlh_seconds += listener.connected_time;
                });

                var tlh_hours = tlh_seconds / 3600;
                return Math.round((tlh_hours + 0.00001) * 100) / 100;
            }
        },
        methods: {
            formatTime (time) {
                let sec_num = parseInt(time, 10);

                let hours = Math.floor(sec_num / 3600);
                let minutes = Math.floor((sec_num - (hours * 3600)) / 60);
                let seconds = sec_num - (hours * 3600) - (minutes * 60);

                if (hours < 10) {
                    hours = '0' + hours;
                }
                if (minutes < 10) {
                    minutes = '0' + minutes;
                }
                if (seconds < 10) {
                    seconds = '0' + seconds;
                }
                return (hours !== '00' ? hours + ':' : '') + minutes + ':' + seconds;
            }
        }
    });

    initMap();

    cb(live_time, live_time);
});
