{% extends 'base_no_lmenu.html' %}{% load i18n %}
{% block main %}
    <script src="https://api-maps.yandex.ru/2.1/?lang={{ LANGUAGE_CODE }}" type="text/javascript"></script>

    <script type="text/javascript">
    /*
     * Data format for struct ServerInfo:
     * {
     *    "1": {
     *        "device": {
     *            "status": "und|unr|up|dwn",
     *            "comment": "title of the device"
     *        }
     *        "devcount": 23,
     *        "latitude": 86.123123,
     *        "longitude": 23.234234,
     *        "title": "some descriptive",
     *        "pk": 1
     *    }
     * }
     * Where:
     *   dot_id - int, id of dot
     *   device - single device info on the dot, if devcount is 1
     *   devcount - count of devices on the dot
     */
    ymaps.ready(init);
    var myMap;

    function placemark_click(e){
        var plcmrk = e.get('target');
        plcmrk.properties.set('balloonContent', "{% trans 'Loading..' %}");
        var html = $.ajax({
          url: "{% url 'mapapp:dot_tooltip' %}",
          data: {'d': plcmrk.properties._data.dot_id},
          async: false
        }).responseText;
        plcmrk.properties.set('balloonContent', html);
    }

    function open_in_new_window(e){
        var data = e.get('target').properties._data;
        var win = window.open("{% url 'mapapp:to_single_dev' %}?dot_id=" + data.dot_id, '_blank');
        if (win)
            win.focus();
        else
            showErr("{% trans 'Please allow popups for this website' %}");
    }

    /*
     * db_info is a struct ServerInfo
     */
    function get_params_for_placemark(db_info){
        var iconname = 'dev.png';
        var click_callback = placemark_click;
        if(db_info.devcount > 1){
            iconname='relay_rack.png';
        }else if(db_info.devcount == 1){
            var dev = db_info.device;
            if(dev.status == 'unr' || dev.status == 'dwn')
                iconname='dev_bug.png';
            else if(dev.status == 'up')
                iconname='dev_ok.png';
            click_callback = open_in_new_window;
        }else
            iconname='flag_black.png';
        return [iconname, click_callback];
    }

    function load_dots(r){
        for(let e of r){
            var params_from_db = get_params_for_placemark(e);

            var stat = '';
            if(e.device != null)
                stat = e.device.status;

            dot_place([e.latitude, e.longitude], {
                hintContent: e.title + stat,
                dot_id: e.pk
            }, params_from_db[1], params_from_db[0]);
        }
    }

    function dot_place(pos, opts, click_callback, icon_name='dev_ok.png'){
        var dot = new ymaps.Placemark(pos, opts, {
            iconLayout: 'default#image',
            iconImageHref: '/static/img/gmarkers/'+icon_name,
            iconImageSize: [32, 48],
            iconImageOffset: [-16, -48]
        });
        dot.events.add('click', click_callback);
        myMap.geoObjects.add(dot);
    }

    function on_success_add_dot(r){
        hide_ModalMyContent();
        var d = $.parseJSON(r);

        if(d.error){
            alert(d.error);
            return false;
        }

        dot_place([d.latitude, d.longitude], {
            hintContent: d.title,
            dot_id: d.pk
        }, placemark_click);
    }

    function add_dot(e){
        var coords = e.get('coords');
        $.get('{% url 'mapapp:modal_add_dot' %}', {'coords': coords.join(',')}, function(r){
            show_ModalMyContent(r);
            $('.form-ajax').ajform({'on_response': on_success_add_dot});
        });
        e.preventDefault();
    }

    function get_placemark_states(){
        $.getJSON("{% url 'mapapp:get_dots' %}?is_obtain_pk=on", update_placemark_states);
    }

    /*
     * states is a associated array of structs ServerInfo
     */
    function update_placemark_states(states){
        var it = myMap.geoObjects.getIterator(), placemark;
        while(placemark = it.getNext()){
            if(placemark.properties === undefined)
                break;
            var server_info = states[placemark.properties._data.dot_id];
            if(server_info === undefined)
                continue;
            var r = get_params_for_placemark(server_info);
            placemark.events.remove('click', open_in_new_window);
            placemark.events.remove('click', placemark_click);
            placemark.events.add('click', r[1]);
            placemark.options.set({'iconImageHref': '/static/img/gmarkers/' + r[0]});
        }
    }

    function init(){

        var win = $(window);

        myMap = new ymaps.Map("yamap", {
            center: [45.449160, 34.735454],
            zoom: 12,
            controls: ['zoomControl', 'geolocationControl']
        });
        myMap.controls.add('typeSelector', {position: {left: 45, top: 10}});

        $.getJSON("{% url 'mapapp:get_dots' %}", load_dots);

        myMap.events.add('dblclick', add_dot);

        $('.mapbtns').on('click', function(){
            $.getJSON($(this).attr('data-href'), function(dot_ids){
                var it = myMap.geoObjects.getIterator(), obj;
                var points = [];
                while(obj = it.getNext()){
                    if(obj.geometry == undefined) break;
                    if(obj.geometry.getType() == "Point"){
                        var dot_id = obj.properties.get('dot_id');
                        var is_dot_contains = dot_ids.includes(dot_id);
                        obj.options.set('visible', is_dot_contains);
                        if(is_dot_contains)
                            points.push(obj);
                    }
                }
                var bnds = ymaps.geoQuery(points).getBounds();
                if(bnds){
                    if(points.length > 1)
                        myMap.setBounds(bnds, {duration: 400, checkZoomRange: true, useMapMargin: true, zoomMargin: 30});
                    else
                        myMap.panTo([points[0].geometry.getCoordinates()]);
                }
            });
            $('.mapbtns').removeClass('active');
            $(this).addClass('active');
        });

        // Two time per minute update placemarks
        var inttime = setInterval(get_placemark_states, 30*1000);

    }
    function showAll(){
        var it = myMap.geoObjects.getIterator(), obj;
        while(obj = it.getNext()){
            if(obj.geometry == undefined) break;
            if(obj.geometry.getType() == "Point"){
                obj.options.set('visible', true);
            }
        }
        myMap.setBounds(myMap.geoObjects.getBounds(), {duration: 400});
        $('.mapbtns').removeClass('active');
    }
    </script>


    <div id="yamap" class="col-sm-12"></div>
    <style>
    #yamap{
        margin-left: -15px;
        margin-top: -9px;
        padding: 0;
        position: fixed;
        height: 95vh;
        width: 100%;
    }
    #yapanel{
        position: absolute;
        right: 12px;
        top: 5px;
    }
    .list-group-item{
        padding: 3px 15px;
    }
    </style>

    <div class="panel panel-default hidden-sm hidden-xs" id="yapanel">
        <div class="panel-heading">
            <h4 class="modal-title">
                {% trans 'Layers' %}
                <a href="https://github.com/nerosketch/djing/blob/master/docs/map.md" title="{% trans 'Help' %}" target="_blank" data-toggle="tooltip">?</a>
            </h4>
        </div>
        <div class="list-group">
            {% for grp in groups %}
            <button type="button" data-href="{% url 'mapapp:resolve_dots_by_group' grp.pk %}" class="list-group-item mapbtns">{{ grp.title }}</button>
            {% endfor %}
        </div>
        <div class="panel-footer">
            <div class="btn-group-vertical btn-group-sm">
                <a href="#" onclick="showAll();" class="btn btn-default">
                    <span class="glyphicon glyphicon-eye-open"></span> {% trans 'Show all' %}
                </a>
                <a href="#" onclick="get_placemark_states();" class="btn btn-default">
                    <span class="glyphicon glyphicon-refresh"></span> {% trans 'Update states' %}
                </a>
            </div>
        </div>
    </div>

{% endblock %}
