/* (C) GeoBasis-DE/LGB
 * Copyright by Landesvermessung und Geobasisinformation Brandenburg (LGB)
 *
 * Software engineering by Intevation GmbH
 *
 * This file is Free Software under the GNU GPL (>=v3)
 * and comes with ABSOLUTELY NO WARRANTY! Check out the
 * LICENSE for details.
 */

/**
 * The View to display the mouse position.
 */
Ext.define('LGB.ext4map.view.MousePosition', {
    extend: 'Ext.toolbar.TextItem',
    alias: 'widget.mouseposition',

    /**
     * The view id. Do not change!
     */
    id: 'mousePosition',

    /**
     * The OpenLayers map object.
     */
    map: null,

    /**
     * The OpenLayers mouse position control.
     */
    mousePos: null,

    digits: 2,

    text: null,

    /**
     * Set the mouse position view to the div of this view.
     */
    afterRender: function() {
        this.superclass.afterRender.apply(this, arguments);
        var me = this;
        this.mousePos = new ol.control.MousePosition({
            coordinateFormat: function(coordinate) {
                return 'E: ' + coordinate[0].toFixed(me.digits) +
                    ' N: ' + coordinate[1].toFixed(me.digits);
            },
            target: this.el.dom
        });
        this.map = Ext.ComponentQuery.query('map')[0].map;
        this.map.addControl(this.mousePos);
        this.text = this.el.dom.childNodes[0];
        this.el.dom.children[0].addEventListener('DOMNodeInserted', function(evt) {
            if (me.el.dom.childNodes.length > 1) {
                me.el.dom.removeChild(me.el.dom.childNodes[0]);
            }
        });
        this.el.dom.children[0].addEventListener('DOMNodeRemoved', function(evt) {
            if (me.el.dom.childNodes.length == 1) {
                me.el.dom.insertBefore(me.text, me.el.dom.childNodes[0]);
            }
        });
    }
});