<?php $this->layout('main', ['title' => __('Listeners'), 'manual' => true]) ?>

<?php
/** @var \App\Assets $assets */
$assets
    ->load('vue')
    ->load('daterangepicker')
    ->load('highmaps')
    ->load('highcharts_theme_'.$customization->getTheme());
?>

<div class="row">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-header ch-alt">
                <div class="row">
                    <div class="col-md-8">
                        <h2><?=__('Listeners') ?></h2>
                        <div><span id="listener-count">0</span> Unique</div>
                    </div>
                    <div class="col-md-4 text-right">
                        <a class="btn btn-default" id="reportrange" href="#">
                            <i class="zmdi zmdi-calendar"></i> <span><?=__('Live Listeners') ?></span> <i class="caret"></i>
                        </a>
                    </div>
                </div>
            </div>
            <div id="map" style="height: 350px;">
            </div>
            <table class="data-table table table-responsive table-striped" id="app-datatable">
                <thead>
                    <tr>
                        <th><?=__('IP') ?></th>
                        <th><?=__('Time (sec)') ?></th>
                        <th><?=__('User Agent') ?></th>
                        <th><?=__('Location') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="listener in listeners">
                        <td>{{ listener.ip }}</td>
                        <td>{{ listener.connected_time }}</td>
                        <td>
                            <span v-if="listener.is_mobile" title="<?=__('Mobile Device') ?>">
                                <i class="zmdi zmdi-smartphone"></i>
                            </span>
                            <span v-else title="<?=__('Desktop Device') ?>">
                                <i class="zmdi zmdi-desktop-windows"></i>
                            </span>
                            {{ listener.user_agent }}
                        </td>
                        <td>
                            <span v-if="listener.location.status == 'success'">
                                {{ listener.location.region }}, {{ listener.location.country }}
                            </span>
                            <span v-else-if="listener.location.message">
                                {{ listener.location.message }}
                            </span>
                            <span v-else>
                                <?=__('Unknown') ?>
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div class="card-body card-padding-sm text-muted">
                <?=__('This product includes GeoLite2 data created by MaxMind, available from %s.', '<a href="http://www.maxmind.com">http://www.maxmind.com</a>') ?>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" nonce="<?=$assets->getCspNonce() ?>">
var live_time, load_timeout, app_datatable, chart;

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

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

    updateListeners(start, end);
}

function initMap() {
    chart = Highcharts.mapChart('map', {
        chart: {
            map: 'custom/world'
        },
        title: {
            text: null
        },
        tooltip: {
            pointFormat: 'IP: {point.ip}<br>' +
                'Country: {point.location.country}<br>' +
                'Region: {point.location.region}<br>' +
                'City: {point.location.city}<br>' +
                'Time connected: {point.connected_time}<br>' +
                'User Agent: {point.user_agent}'
        },
        mapNavigation: {
            enabled: true,
            buttonOptions: {
                verticalAlign: 'bottom'
            }
        },
        series: [
            {
                name: 'Basemap',
                borderColor: '#A0A0A0',
                nullColor: 'rgba(200, 200, 200, 0.7)',
                showInLegend: false
            },
            {
                type: 'mappoint',
                data: [],
                name: <?=$this->escapeJs(__('Listener')) ?>
            }
        ]
    });
}

/*
 * Live map updating based on parasprite-Radio by djazz:
 * https://github.com/daniel-j
 */
function setMapPoints(points) {
    $.each(chart.series[1].data, function(i, existing_point) {
        chart.series[1].removePoint(i, false);
    });

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

        l.lat = l.location.lat;
        l.lon = l.location.lon;

        chart.series[1].addPoint(l, false);
    });

    chart.redraw();
}

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

    var params = {};
    if (!is_live) {
        params.start = start.format('YYYY-MM-DD');
        params.end = end.format('YYYY-MM-DD');
    }

    $.getJSON('<?=$router->named('api:listeners:index', ['station' => $station->getId()]) ?>', params, function (data) {
        app_datatable.listeners = data;

        $('#listener-count').text(data.length);

        setMapPoints(data);

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

$(function() {

    live_time = moment(0);

    $('#reportrange').daterangepicker({
        startDate: live_time,
        endDate: live_time,
        opens: "left",
        ranges: {
            "<?=__('Live Listeners') ?>": [moment(0), moment(0)],
            "<?=__('Today') ?>": [moment(), moment()],
            "<?=__('Yesterday') ?>": [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            "<?=__('Last 7 Days') ?>": [moment().subtract(6, 'days'), moment()],
            "<?=__('Last 30 Days') ?>": [moment().subtract(29, 'days'), moment()],
            "<?=__('This Month') ?>": [moment().startOf('month'), moment().endOf('month')],
            "<?=__('Last Month') ?>": [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        }
    }, cb);

    app_datatable = new Vue({
        el: '#app-datatable',
        data: {
            listeners: []
        }
    });

    initMap();

    cb(live_time, live_time);
});
</script>
