/*
 * uNav http://launchpad.net/unav
 * Copyright (C) 2015-2016 Marcos Alvarez Costales https://launchpad.net/~costales
 * Copyright (C) 2015-2016 JkB https://launchpad.net/~joergberroth
 * Copyright (C) 2016 Nekhelesh Ramananthan https://launchpad.net/~nik90
 *
 * uNav is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * uNav is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

import QtQuick 2.4
import Ubuntu.Web 0.2
import Ubuntu.Components 1.3
import QtQuick.Layouts 1.1
import Ubuntu.Components.Popups 1.3
import Qt.labs.settings 1.0
import com.canonical.Oxide 1.9 as Oxide
import Ubuntu.Content 1.1
import QtMultimedia 5.0
import QtFeedback 5.0
import QtSystemInfo 5.0
import QtQuick.XmlListModel 2.0
import "components"
import "js/utils.js" as QmlJs

MainView {
    id: navApp

    objectName: "navApp"
    applicationName: "navigator.costales"

    Component.onCompleted: {
        // Translations
        i18n.domain = "unav";
        i18n.bindtextdomain("unav", "nav/locales/mo");
    }
    
    anchorToKeyboard: true
    
    width: units.gu(150)
    height: units.gu(100)

    property string applicationVersion: "0.59"
    property string mapUrl: "../nav/index.html"
    property string appUA: "Mozilla/5.0 (Linux; Android 5.0; Nexus 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.102 Mobile Safari/537.36"

    // persistent app settings:
    property var settings: Settings {
        property int soundIndications: 0 // 0 voice 1 notification 2 none
        property int unit: 0
        property int routingMode: 0 // 0 car, 1 walk, 2 bicycle
        property bool avoidTolls: false
        property bool alertRadars: false
        property bool legalRadarShow: true
        property string prevLat: ''
        property string prevLng: ''
        property int prevZoom: 9999
        property bool uiShowSpeed: false
        property bool saveHistory: true
        property bool headerVisible: true
        property bool showTuto: true
        property int defaultDistancePOI: 1
    }
    
    ScreenSaver {
        id: screenSaver
        screenSaverEnabled: !Qt.application.active
    }

    PageStack {
        id: mainPageStack

        Component.onCompleted: if (navApp.settings.showTuto) mainPageStack.push(Qt.resolvedUrl("tuto/WelcomeWizard.qml"))
        
        property string currentLat: "null"
        property string currentLng: "null"
        property string endLat: "null"
        property string endLng: "null"
        property string clickedLat: "null"
        property string clickedLng: "null"
        property string ptFromLat: "null"
        property string ptFromLng: "null"
        property string routeState: "no"
        property int center_onpos: 0 // 0 GPS off, 1 GPS on + not center, 2 GPS on + center
        property bool favPopup: false
        property bool onLoadingExecuted: false


        property string usContext: "messaging://"
        // Workaround: as long as map keeps a webcontainer this function handles js events to the webview.
        function executeJavaScript(code) {
            var req = webview.rootFrame.sendMessage(mainPageStack.usContext, "EXECUTE", {code: code});
            //req.onreply = function (msg) {
            //console.log(msg.str);
            //}
            req.onerror = function (code, explanation) {
                console.log("Error " + code + ": " + explanation)
            }
        }

        Page {
            id: navigationPage
            
            visible: mainPageStack.depth === 0
            
            property bool buttonsEnabled: false
            
            anchors.fill: parent
            
            header: UNavHeader {
                id: header

                title: "uNav"
                visible: navApp.settings.headerVisible

                leadingActionBar {
                    width: 0
                    visible: false
                }
                
                trailingActionBar {
                    numberOfSlots: 4
                    actions: [
                        Action {
                            id: actionSettings
                            iconName: "settings"
                            text: i18n.tr("Settings")
                            enabled: navigationPage.buttonsEnabled
                            onTriggered: {
                                goThereActionPopover.hide();
                                mainPageStack.push(Qt.resolvedUrl("SettingsPage.qml"));
                            }
                        },

                        Action {
                            id: centerPosAction
                            iconName: mainPageStack.center_onpos ? "media-optical-symbolic" : "gps"
                            text: i18n.tr("Center on Position")
                            enabled: navigationPage.buttonsEnabled && mainPageStack.center_onpos !== 2
                            onTriggered: {
                                mainPageStack.center_onpos = 2;
                                goThereActionPopover.hide();
                                mainPageStack.executeJavaScript("center_pos()");
                            }
                        },

                        Action {
                            id: searchAction
                            iconName: "find"
                            text: i18n.tr("Search")
                            enabled: navigationPage.buttonsEnabled
                            onTriggered: {
                                goThereActionPopover.hide();
                                mainPageStack.push(Qt.resolvedUrl("SearchPage.qml"))
                            }
                        },

                        Action {
                            id: cancelAction
                            iconSource: Qt.resolvedUrl("../nav/img/header/nav-actions.svg")
                            text: i18n.tr("Destination")
                            visible: mainPageStack.routeState !== 'no'
                            enabled: navigationPage.buttonsEnabled
                            onTriggered: {
                                goThereActionPopover.hide();
                                goThereActionPopover.showMenu = true;
                                goThereActionPopover.show();
                            }
                        }
                    ]
                }
            }

            /**
            Workaround:
            QML Map Element currently does not support flicking. This makes it unusable to this app so far.
            As long as this is to supported, the map view falls back to a html5 container that renders the navigation.
            Signals from qml are sent via eventhandlers in oxide via userScript.
            The panel stays in html5, too, for ease of integration.
            **/

            WebContext {
                id: webcontext
                userAgent: appUA
                userScripts: [
                    Oxide.UserScript {
                        context: mainPageStack.usContext
                        url: Qt.resolvedUrl("js/oxide.js")
                    }
                ]
            }

            WebView {
                id: webview
                anchors.fill: parent
                z: -6
                context: webcontext
                url: mapUrl
                preferences.allowFileAccessFromFileUrls: true
                preferences.allowUniversalAccessFromFileUrls: true
                preferences.appCacheEnabled: true
                preferences.javascriptCanAccessClipboard: true
                preferences.javascriptEnabled: true
                //not used right now:
                //filePicker: filePickerLoader.item

                // get in-webcontainer click events (e.g. click on map)
                // and coordinates to handle them in qml ui:
                onNavigationRequested:{
                    // We could start to clean this up a bit by writing functions on that...
                    var url = request.url.toString().split("?");
                    var params = url[1].split("/");
                    switch (url[0]) {
                        case "http://go/":
                            Qt.openUrlExternally(url[1]);
                            break;
                        
                        case "http://get_routeinfo_list/":
                            goThereActionPopover.hide();
                            var dec_routeList = decodeURIComponent(url[1]);
                            mainPageStack.push(Qt.resolvedUrl("RouteInfoListPage.qml"), { routeList: JSON.parse(dec_routeList) });
                            navApp.settings.headerVisible = true;
                            break;
                        
                        case "http://route_status/":
                            mainPageStack.currentLat = params[0];
                            mainPageStack.currentLng = params[1];
                            mainPageStack.endLat = params[2];
                            mainPageStack.endLng = params[3];
                            mainPageStack.routeState = params[4];
                            break;
                        
                        case "http://clicked_on_map/":
                            goThereActionPopover.hide();
                            goThereActionPopover.osm_type = 'none';
                            goThereActionPopover.osm_id = 'none';
                            goThereActionPopover.phone = '';
                            goThereActionPopover.poiName = "";
                            
                            if (params[0] === 'nofollow' && mainPageStack.center_onpos === 2)
                                mainPageStack.center_onpos = 1;
                            
                            mainPageStack.clickedLat = params[1];
                            mainPageStack.clickedLng = params[2];
                            
                            if (params[3] !== 'none')
                                goThereActionPopover.osm_type = params[3];
                            
                            if (params[4] !== 'none')
                                goThereActionPopover.osm_id = params[4];
                            
                            if (params[5] !== 'none')
                                goThereActionPopover.phone = params[5];
                            
                            if (params[6] !== "none")
                                goThereActionPopover.poiName = params[6].replace(/¿¿¿/g, "\/");
                                
                            mainPageStack.favPopup = false;
                            goThereActionPopover.show();

                            // Perform reverse geocoding only when it is a generic marker that the user clicked on the map
                            if (goThereActionPopover.poiName === "" && goThereActionPopover.osm_id === 'none') {
                                reverseXmlModel.reverseSearch(mainPageStack.clickedLat, mainPageStack.clickedLng);
                            }
                            break;
                        
                        case "http://hide_popup/":
                            goThereActionPopover.hide();
                            break;
                            
                        case "http://set_center_onpos/":
                            switch (params[0]) {
                                case '0': // GPS Denied (special)
                                    mainPageStack.routeState = 'no';
                                    mainPageStack.center_onpos = 0;
                                    break;
                                case '1':
                                    mainPageStack.center_onpos = 1;
                                    break;
                                case '2':
                                    mainPageStack.center_onpos = 2;
                                    break;
                            }
                            break;
                            
                        case "http://set_ui_speed/":
                            if (params[0] === 'true')
                                navApp.settings.uiShowSpeed = true;
                            else
                                navApp.settings.uiShowSpeed = false;
                            break;
                            
                        case "http://cancel_route/":
                            mainPageStack.routeState = 'no';
                            break;
                        
                        case "http://save_pos/":
                            navApp.settings.prevLat = params[0];
                            navApp.settings.prevLng = params[1];
                            navApp.settings.prevZoom = params[2];
                            break;
                    }
                    
                    request.action = Oxide.NavigationRequest.ActionReject;
                }

                Component.onCompleted: {
                    preferences.localStorageEnabled = true
                }

                onLoadingStateChanged: {
                    if (!loading && !mainPageStack.onLoadingExecuted) {
                        mainPageStack.onLoadingExecuted = true;
                        //send saved Setting states:
                        mainPageStack.executeJavaScript("settings.set_sound(" + navApp.settings.soundIndications + ");");
                        mainPageStack.executeJavaScript("settings.set_unit(\'" + ( navApp.settings.unit === 0 ? "km" : "mi" ) +"\');");
                        mainPageStack.executeJavaScript("ui.set_scale_unit(\'" + ( navApp.settings.unit === 0 ? "km" : "mi" ) +"\');");
                        mainPageStack.executeJavaScript("settings.set_routing_mode(" + navApp.settings.routingMode + ");");
                        mainPageStack.executeJavaScript("settings.set_avoid_tolls(" + navApp.settings.avoidTolls + ");");
                        mainPageStack.executeJavaScript("settings.set_alert_radars(" + navApp.settings.alertRadars + ");");
                        mainPageStack.executeJavaScript("settings.set_ui_speed(" + navApp.settings.uiShowSpeed + ");");
                        
                        // Center map in last position
                        if (navApp.settings.prevLat !== '' && navApp.settings.prevLng !== '' && navApp.settings.prevLat !== null && navApp.settings.prevLng !== null && navApp.settings.prevZoom !== 9999) {
                            mainPageStack.executeJavaScript("map.getView().setCenter(ol.proj.transform([" + navApp.settings.prevLng + "," + navApp.settings.prevLat + "], 'EPSG:4326', 'EPSG:3857')); map.getView().setZoom(" + navApp.settings.prevZoom + ");");
                        }
                        
                        // Hack: If user click so fast in buttons, app breaks sometimes
                        navigationPage.buttonsEnabled = true;
                        
                        // Catching urls
                        var url_dispatcher = Qt.application.arguments[1];
                        if (QmlJs.is_url_dispatcher(url_dispatcher)['is_dispatcher']) {
                            var coord = QmlJs.get_url_coord(url_dispatcher);
                            if (coord['lat'] !== null && coord['lng'] !== null) {
                                mainPageStack.clickedLat = coord['lat'];
                                mainPageStack.clickedLng = coord['lng'];
                                if (mainPageStack.center_onpos === 2)
                                    mainPageStack.center_onpos = 1;
                                mainPageStack.executeJavaScript("ui.markers_POI_set([{title: \"" + i18n.tr("Shared Position") + "\", lat: " + mainPageStack.clickedLat + ", lng: " + mainPageStack.clickedLng + "}])");
                                mainPageStack.favPopup = false;
                                goThereActionPopover.show();
                            }
                        }
                    }
                }

                onGeolocationPermissionRequested: { request.allow() }
            }

            Connections {
                target: UriHandler
                onOpened: {
                    if (uris.length === 0 ) {
                        return;
                    }
                    // Catching urls
                    var url_dispatcher = uris[0];
                    if (QmlJs.is_url_dispatcher(url_dispatcher)['is_dispatcher']) {
                        var coord = QmlJs.get_url_coord(url_dispatcher);
                        if (coord['lat'] !== null && coord['lng'] !== null) {
                            mainPageStack.clickedLat = coord['lat'];
                            mainPageStack.clickedLng = coord['lng'];
                            if (mainPageStack.center_onpos === 2)
                                mainPageStack.center_onpos = 1;
                            mainPageStack.executeJavaScript("ui.markers_POI_set([{title: \"" + i18n.tr("Shared Position") + "\", lat: " + mainPageStack.clickedLat + ", lng: " + mainPageStack.clickedLng + "}])");
                            mainPageStack.favPopup = false;
                            goThereActionPopover.show();
                        }
                    }
                }
            }

            Loader {
                id: actionButtonRowLoader
                sourceComponent: !header.visible ? actionButtonRowComponent : undefined
                anchors { right: parent.right; top: parent.top; margins: units.gu(1) }
            }

            Component {
                id: actionButtonRowComponent
                Row {
                    id: actionButtonRow

                    opacity: navigationPage.buttonsEnabled ? 1.0 : 0.2

                    ActionIcon {
                        icon.source: Qt.resolvedUrl("../nav/img/header/nav-actions-transparent.svg")
                        enabled: navigationPage.buttonsEnabled
                        visible: mainPageStack.routeState !== 'no'
                        onClicked: {
                            goThereActionPopover.hide();
                            goThereActionPopover.showMenu = true;
                            goThereActionPopover.show();
                        }
                    }

                    ActionIcon {
                        icon.name: "find"
                        enabled: navigationPage.buttonsEnabled
                        onClicked: {
                            goThereActionPopover.hide();
                            mainPageStack.push(Qt.resolvedUrl("SearchPage.qml"))
                        }
                    }

                    ActionIcon {
                        icon.name: mainPageStack.center_onpos ? "media-optical-symbolic" : "gps"
                        enabled: navigationPage.buttonsEnabled && mainPageStack.center_onpos !== 2
                        onClicked: {
                            mainPageStack.center_onpos = 2;
                            goThereActionPopover.hide();
                            mainPageStack.executeJavaScript("center_pos()");
                        }
                    }

                    ActionIcon {
                        icon.name: "settings"
                        enabled: navigationPage.buttonsEnabled
                        onClicked: {
                            goThereActionPopover.hide();
                            mainPageStack.push(Qt.resolvedUrl("SettingsPage.qml"));
                        }
                    }
                }
            }

            ZoomButtons {
                id: zoomButtons
                visible: navigationPage.buttonsEnabled
                onZoomedIn: mainPageStack.executeJavaScript("custom_zoom(1)")
                onZoomedOut: mainPageStack.executeJavaScript("custom_zoom(-1)")
            }

            XmlListModel {
                id: reverseXmlModel

                readonly property string baseUrl: "https://nominatim.openstreetmap.org/reverse?format=xml&email=costales.marcos@gmail.com&addressdetails=0&extratags=1&zoom=18&namedetails=1&"

                function reverseSearch(lat, lon) {
                    source = (baseUrl + "lat=" + lat + "&lon=" + lon) ;
                }

                function clear() {
                    goThereActionPopover.reverseGeoString = "";
                    source = "";
                }

                onStatusChanged: {
                    if (status === XmlListModel.Error || (status === XmlListModel.Ready && count === 0)) {
                        goThereActionPopover.reverseGeoString = ""
                        console.log("Error reverse geocoding the location!")
                    }

                    else if (status === XmlListModel.Ready && count > 0) {
                        // Check if the location returned by reverse geocoding is a POI by looking for the existence of certain parameters
                        // like cuisine, phone, opening_hours, internet_access, wheelchair etc that do not apply to a generic address.
                        if (reverseXmlModel.get(0).description || reverseXmlModel.get(0).cuisine || reverseXmlModel.get(0).phone || reverseXmlModel.get(0).opening_hours
                                || reverseXmlModel.get(0).website && reverseXmlModel.get(0).wheelchair || reverseXmlModel.get(0).internet_access) {

                            // Check if the name, osm_id and osm_type are valid, otherwise the POI popup will break.
                            if (reverseXmlModel.get(0).name && reverseXmlModel.get(0).osm_id && reverseXmlModel.get(0).osm_type) {
                                goThereActionPopover.poiName = reverseXmlModel.get(0).name
                                goThereActionPopover.osm_id = reverseXmlModel.get(0).osm_id
                                goThereActionPopover.osm_type = reverseXmlModel.get(0).osm_type.charAt(0).toUpperCase()
                                goThereActionPopover.phone = reverseXmlModel.get(0).phone
                            } else {
                                goThereActionPopover.reverseGeoString = reverseXmlModel.get(0).result
                            }
                        }

                        // If nothing works, fall back to just showing the address in a generic popup
                        else {
                            goThereActionPopover.reverseGeoString = reverseXmlModel.get(0).result
                        }
                    }
                }

                source: ""
                query: "/reversegeocode"

                XmlRole { name: "osm_type"; query: "result/@osm_type/string()" }
                XmlRole { name: "osm_id"; query: "result/@osm_id/string()" }
                XmlRole { name: "result"; query: "result/string()" }
                XmlRole { name: "name"; query: "namedetails/name/string()" }
                XmlRole { name: "description"; query: "extratags/tag[@key='description']/@value/string()" }
                XmlRole { name: "cuisine"; query: "extratags/tag[@key='cuisine']/@value/string()" }
                XmlRole { name: "phone"; query: "extratags/tag[@key='phone']/@value/string()" }
                XmlRole { name: "opening_hours"; query: "extratags/tag[@key='opening_hours']/@value/string()" }
                XmlRole { name: "website"; query: "extratags/tag[@key='website']/@value/string()" }
                XmlRole { name: "internet_access"; query: "extratags/tag[@key='internet_access']/@value/string()" }
                XmlRole { name: "wheelchair"; query: "extratags/tag[@key='wheelchair']/@value/string()" }
            }

            PoiPopup {
                id: goThereActionPopover

                // Dragons be here! Don't change these values
                hidePosition: -3*height
                showPosition: navApp.settings.headerVisible ? 0 : -navigationPage.header.height
                anchors { top: navigationPage.header.bottom }

                height: mainContentLoader.height + 2*mainContentLoader.anchors.margins

                property string reverseGeoString: ""
                property string poiName
                property string osm_type
                property string osm_id
                property string phone
                property bool showMenu: false

                onIsShownChanged: {
                    if (!goThereActionPopover.isShown) {
                        reverseXmlModel.clear()
                        goThereActionPopover.showMenu = false
                    }
                }

                Loader {
                    id: mainContentLoader

                    sourceComponent: {
                        if (goThereActionPopover.isShown) {
                            if (goThereActionPopover.showMenu) {
                                return routeMenu
                            }

                            if (goThereActionPopover.osm_id === 'none') {
                                return genericPopupComponent
                            } else {
                                return poiPopupComponent
                            }
                        }

                        else {
                            return undefined
                        }
                    }

                    anchors { top: parent.top; left: parent.left; right: parent.right; margins: units.gu(2) }
                }

                Component {
                    id: routeMenu
                    Item {
                        width: parent.width
                        height: routePageGrid.height
                        
                        Component.onCompleted: {
                            mainPageStack.executeJavaScript("qml_set_route_status();")
                        }
                        
                        CustomGridView {
                            id: routePageGrid

                            ListModel {
                                id: routePageModel
                                Component.onCompleted: initialize()

                                function initialize() {
                                    routePageModel.append({mode: "DESTINATION", text: i18n.tr("NearBy Destination"), iconName: "location"})
                                    routePageModel.append({mode: "CANCEL", text: i18n.tr("Cancel Route"), iconName: "dialog-error-symbolic"})
                                }
                            }

                            itemWidth: units.gu(9)
                            model: routePageModel
                            anchors.horizontalCenter: parent.horizontalCenter

                            delegate: GridDelegate {
                                id: delegate

                                width: units.gu(9)
                                title: model.text
                                icon.name: model.iconName

                                onClicked: {
                                    if (model.mode === "DESTINATION") {
                                        mainPageStack.push(Qt.resolvedUrl("PoiPage.qml"), {"lat": mainPageStack.endLat, "lng": mainPageStack.endLng})
                                    } else if (model.mode === "CANCEL") {
                                        mainPageStack.routeState = 'no';
                                        mainPageStack.executeJavaScript("click_cancel_route();");
                                        mainPageStack.pop();
                                    }
                                    goThereActionPopover.showMenu = false
                                    goThereActionPopover.hide()
                                }
                            }
                        }
                    }
                }

                Component {
                    id: genericPopupComponent
                    Column {
                        spacing: units.gu(2)

                        Label {
                            id: geoCodeLabel
                            maximumLineCount: 3
                            width: parent.width
                            wrapMode: Text.WordWrap
                            color: UbuntuColors.slate
                            horizontalAlignment: Text.AlignHCenter
                            textSize: !truncated ? Label.Large : Label.Medium
                            text: goThereActionPopover.reverseGeoString ? goThereActionPopover.reverseGeoString
                                                                        : i18n.tr("Coord: %1, %2").arg(parseFloat(mainPageStack.clickedLat).toFixed(5)).arg(parseFloat(mainPageStack.clickedLng).toFixed(5));
                        }

                        Row {
                            spacing: units.gu(0.5)
                            anchors.horizontalCenter: parent.horizontalCenter

                            GridIconDelegate {
                                icon.name: "send"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                visible: goThereActionPopover.poiName !== i18n.tr("Current Position") ? true : false
                                onClicked: {
                                    goThereActionPopover.hide();
                                    mainPageStack.center_onpos = 2;
                                    mainPageStack.routeState = 'yes';
                                    mainPageStack.executeJavaScript("calc2coord(" + mainPageStack.clickedLat + ", " + mainPageStack.clickedLng + ");");
                                }
                            }

                            GridIconDelegate {
                                icon.name: mainPageStack.favPopup ? "starred" : "non-starred"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    mainPageStack.favPopup = !mainPageStack.favPopup;
                                    mainPageStack.push(Qt.resolvedUrl("SearchPage.qml"), {addFavoriteFromMap: true, favLat: mainPageStack.clickedLat, favLng: mainPageStack.clickedLng, favName: ""});
                                }
                            }

                            GridIconDelegate {
                                icon.name: "location"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    mainPageStack.push(Qt.resolvedUrl("PoiPage.qml"), {"lat": mainPageStack.clickedLat, "lng": mainPageStack.clickedLng})
                                }
                            }

                            GridIconDelegate {
                                icon.name: "share"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    mainPageStack.push(Qt.resolvedUrl("Share.qml"), {"lat": mainPageStack.clickedLat, "lon": mainPageStack.clickedLng})
                                }
                            }

                            GridIconDelegate {
                                icon.name: "transfer-progress-upload"
                                visible: mainPageStack.ptFromLat === "null"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    goThereActionPopover.hide();
                                    mainPageStack.ptFromLat = mainPageStack.clickedLat;
                                    mainPageStack.ptFromLng = mainPageStack.clickedLng;
                                }
                            }

                            GridIconDelegate {
                                icon.name: "transfer-progress-download"
                                visible: mainPageStack.ptFromLat !== "null"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    goThereActionPopover.hide();
                                    mainPageStack.routeState = 'simulate_calculating';
                                    mainPageStack.executeJavaScript("simulate2coord(" + mainPageStack.ptFromLat + ", " + mainPageStack.ptFromLng + ", " + mainPageStack.clickedLat + ", " + mainPageStack.clickedLng + ");");
                                    mainPageStack.ptFromLat = "null";
                                }
                            }
                        }
                    }
                }

                Component {
                    id: poiPopupComponent
                    Column {
                        spacing: units.gu(2)

                        Label {
                            text: goThereActionPopover.poiName
                            visible: goThereActionPopover.poiName !== ""
                            maximumLineCount: 2
                            width: parent.width
                            horizontalAlignment: Text.AlignHCenter
                            textSize: Label.Large
                            elide: Text.ElideRight
                            wrapMode: Text.WordWrap
                            color: UbuntuColors.slate
                        }

                        Row {
                            spacing: units.gu(2)
                            anchors.horizontalCenter: parent.horizontalCenter

                            GridIconDelegate {
                                icon.name: "send"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    goThereActionPopover.hide();
                                    mainPageStack.center_onpos = 2;
                                    mainPageStack.routeState = 'yes';
                                    mainPageStack.executeJavaScript("calc2coord(" + mainPageStack.clickedLat + ", " + mainPageStack.clickedLng + ");");
                                }
                            }

                            GridIconDelegate {
                                icon.name: "call-start"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                visible: goThereActionPopover.phone !== ""
                                onClicked: {
                                    Qt.openUrlExternally("tel:///" + goThereActionPopover.phone)
                                }
                            }

                            GridIconDelegate {
                                icon.name: "info"
                                icon.height: units.gu(3)
                                highlightSize: units.gu(-1)
                                onClicked: {
                                    goThereActionPopover.hide();
                                    mainPageStack.push(Qt.resolvedUrl("PoiDetailsPage.qml"), {osm_id: goThereActionPopover.osm_id, osm_type: goThereActionPopover.osm_type, poiName: goThereActionPopover.poiName})
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Connections {
        target: Qt.application
        onStateChanged:
            if(Qt.application.state !== Qt.ApplicationActive) {
                goThereActionPopover.hide();
                mainPageStack.executeJavaScript("qml_save_pos();");
            }
    }
}
