/****************************************************************************
**
** Copyright (C) 2019-2023 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
** Copyright (C) 2019-2023 General Magic B.V., info@generalmagic.com
**
** BSD License Usage
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Klarälvdalens Datakonsult AB nor the names of
**     its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
****************************************************************************/

//! [MapView code]
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtQuick.Window 2.12
import GeneralMagic 2.0
import FpsCounter 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("MarkersProgrammatic")
    property var updater: ServicesManager.contentUpdater(ContentItem.Type.RoadMap)
    Component.onCompleted: {
        //! [Set token safely]
        ServicesManager.settings.token = __my_secret_token;
        //! [Set token safely]

        ServicesManager.logLevel = ServicesManager.Error;
        ServicesManager.settings.allowInternetConnection = true; // enable connection to online services

        updater.autoApplyWhenReady = true;
        updater.update();
    }

    FpsCounter {
        id: fpsCounter
    }

    function createSketchesPoi(lat, lon)//sketches-type markers - cannot be grouped;
    {
        let coords = ServicesManager.createCoordinates(lat,lon,0);//lat,lon,alt

        /////////////////////////////////
        //the following optional block is used only to enable autocenter on landmark group
        //and to render a route between the individual landmarks/waypoints/icons;
        {
            //Creates a landmark that is owned by the routingWaypoints, for efficiency.
            //This is required because
            //routingWaypoints.append(lmk);
            //will clone the landmark unless the owner is the routingWaypoints list itself.
            let lmk = ServicesManager.createLandmark(routingWaypoints);
            lmk.coordinates = coords;
            routingWaypoints.append(lmk);
        }
        /////////////////////////////////

        return coords;
    }

    function createMarkerPoi(lat, lon)//regular markers - can be grouped;
    {
        let coords = ServicesManager.createCoordinates(lat,lon,0);//lat,lon,alt
        let marker = ServicesManager.createMarker();
        marker.append(coords);

        /////////////////////////////////
        //the following optional block is used only to enable autocenter on landmark group
        //and to render a route between the individual landmarks/waypoints/icons;
        {
            //Creates a landmark that is owned by the routingWaypoints, for efficiency.
            //This is required because
            //routingWaypoints.append(lmk);
            //will clone the landmark unless the owner is the routingWaypoints list itself.
            let lmk = ServicesManager.createLandmark(routingWaypoints);
            lmk.coordinates = coords;
            routingWaypoints.append(lmk);
        }
        /////////////////////////////////

        return marker;
    }

    /////////////////////////////////
    //the following block is used only to enable autocenter on landmark group
    //and to render a route between the individual landmarks/waypoints/icons;
    LandmarkList {
        id: routingWaypoints
    }
    /////////////////////////////////

    /////////////////////////////////
    //a RoutingService is defined, used in this example only to
    //compute and render a route plotted using list of waypoints/landmarks
    //in the order in which they were added to the list;
    //this block is not required to autocenter on the landmark group;
    //set internet connection to true in the Component.onCompleted block
    //for route computation and rendering to work;
    RoutingService {
        id: routingService
        type: Route.Type.Fastest
        transportMode: Route.TransportMode.Car
        // The list of waypoints is made available to the routing service.
        waypoints: routingWaypoints
        onFinished: {
            map.routeCollection.set(routeList);
            map.centerOnRouteList(routeList);
        }
    }
    /////////////////////////////////

    MapView {
        id: map
        anchors.fill: parent
        viewAngle: 25
        zoomLevel: 69
        viewPerspective: MapView.ViewPerspective.View3D
        buildingsVisibility: MapView.BuildingsVisibility.Show3D
        detailsQualityLevel: MapView.DetailsQualityLevel.Medium

        Text {
            anchors.right: parent.right
            anchors.top: parent.top
            text: fpsCounter.fps
        }
        Button {
            anchors.left: parent.left
            anchors.bottom: parent.bottom
            enabled: routingWaypoints.length
            text: qsTr("Render route")
            onClicked: {
            //render route when button is clicked only if there are waypoints in the list;
            if (routingWaypoints.length)
                {
                //compute and render a route plotted using list of waypoints/landmarks
                //in the order in which they were added
                routingService.update()
                }
            }
        }
        Button {
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            text: qsTr("Clear route")
            onClicked: {
                //delete route when button is clicked;
                //compute and render a route plotted using list of waypoints/landmarks
                //in the order in which they were added
                routingWaypoints.clear()
                routingService.update()
            }
        }
        ColumnLayout {
        Button {
            //anchors.left: parent.left
            //anchors.top: parent.top
            text: map.markerCollection.listCount>0
                ? qsTr("Clear icons"): qsTr("Add icons")
            onClicked: {
            if (map.markerCollection.listCount>0)
            {
                //show how to clear icons from the map;
                //clear the list of points used for centering on the bounding box
                //containing all points/landmarks/waypoints/markers/icons;
                routingWaypoints.clear();
                //also clear the markerlist used for rendering the points on the map;
                //the same set of coordinates is in each of these lists, so both must
                //be cleared;
                //the marker object containing the coordinates for all icons is in the
                //list at index 0, as it is the first object added to the list, so
                //remove the object at index 0, then redraw/refresh the map, which
                //causes the icons to disappear from the map;
                map.markerCollection.removeList(0);//markers
                map.update();
            }
            else
            {
                //regular markers - can be grouped;
                let markerlist = ServicesManager.createMarkerList(MarkerList.Type.Point);
                let markerListRenderSettings = ServicesManager.createMarkerListRenderSettings();
                markerListRenderSettings.imageSize = 32;
                markerListRenderSettings.icon = ServicesManager.createIconFromFile("qrc:/violetcircle.png");
                markerListRenderSettings.labelingMode = MarkerRenderSettings.Group;
                markerListRenderSettings.pointsGroupingZoomLevel = 98;
                markerListRenderSettings.lowDensityPointsGroupMaxCount = 6;
                markerListRenderSettings.lowDensityPointsGroupIcon = ServicesManager.createIconFromFile("qrc:/redcircle.png");
                //markerListRenderSettings.lowDensityPointsGroupIcon = ServicesManager.createIconFromId(Icon.RedBall);
                markerListRenderSettings.mediumDensityPointsGroupMaxCount = 9;
                markerListRenderSettings.mediumDensityPointsGroupIcon = ServicesManager.createIconFromFile("qrc:/greensquare.png");
                //markerListRenderSettings.mediumDensityPointsGroupIcon = ServicesManager.createIconFromId(Icon.GreenBall);
                markerListRenderSettings.highDensityPointsGroupMaxCount = 12;
                markerListRenderSettings.highDensityPointsGroupIcon = ServicesManager.createIconFromFile("qrc:/bluetriangle.png");
                //markerListRenderSettings.highDensityPointsGroupIcon = ServicesManager.createIconFromId(Icon.BlueBall);

                console.log(markerListRenderSettings);

                //set a map style configured in qml.qrc, and located in the project directory;
                //choose one map style line and uncomment it;
                //map.stylePath = "qrc:/Basic_1_Night_Blues_with_Elevation-1_5_688.style";
                map.stylePath = "qrc:/Basic_1_Oldtime_with_Elevation-1_12_657.style";

                //if the list is not cleared, it will grow every time the button is clicked;
                routingWaypoints.clear();//clear the list before adding points;

                //regular markers - can be grouped;
                //latitude and longitude of each icon to be added to the map
                markerlist.append(createMarkerPoi(61.3,8.66));//lat,lon
                markerlist.append(createMarkerPoi(61.3,8.7));//lat,lon
                markerlist.append(createMarkerPoi(61.3,8.74));//lat,lon
                markerlist.append(createMarkerPoi(61.3,8.9));//lat,lon
                markerlist.append(createMarkerPoi(61.3,8.5));//lat,lon
                markerlist.append(createMarkerPoi(61.2,8.7));//lat,lon
                markerlist.append(createMarkerPoi(61.4,8.7));//lat,lon
                markerlist.append(createMarkerPoi(61.28,8.7));//lat,lon
                markerlist.append(createMarkerPoi(61.32,8.7));//lat,lon
                markerlist.append(createMarkerPoi(61.24,8.62));//lat,lon
                markerlist.append(createMarkerPoi(61.24,8.78));//lat,lon
                markerlist.append(createMarkerPoi(61.36,8.62));//lat,lon
                markerlist.append(createMarkerPoi(61.36,8.78));//lat,lon

                //add the settings, such as icon image size, to the markers;

                //MARKERS
                map.markerCollection.appendList(markerlist, markerListRenderSettings);

                console.log("marker collection len:"+map.markerCollection.listCount);
                console.log("markerlist len:"+markerlist.length);

                //the following block is used only to autocenter on the group of landmarks;
                {
                    map.centerOnGeographicArea(routingWaypoints.boundingBox)
                }
            }
            }
        }
        Button {
                //anchors.left: parent.left
                //anchors.top: parent.top
                text: "Add sketches"
                onClicked: {
                //sketches-type markers - cannot be grouped;
                let marker = ServicesManager.createMarker();
                let markerRenderSettings = ServicesManager.createMarkerRenderSettings();
                markerRenderSettings.imageSize = 32;
                //the following line sets a custom icon image;
                //choose one icon image line and uncomment it;
                //the icon image is configured in qml.qrc, and located in the project directory;
                //if an icon image is not set, markers will be shown as blue dots;
                markerRenderSettings.icon = ServicesManager.createIconFromFile("qrc:/redcircle.png")
                //markerRenderSettings.icon = ServicesManager.createIconFromFile("qrc:/greensquare.png")
                //markerRenderSettings.icon = ServicesManager.createIconFromFile("qrc:/bluetriangle.png")

                console.log(markerRenderSettings);

                //if the list is not cleared, it will grow every time the button is clicked;
                routingWaypoints.clear();//clear the list before adding points;

                //sketches-type markers - cannot be grouped;
                //latitude and longitude of each icon to be added to the map
                marker.append(createSketchesPoi(61.3,7.16));//lat,lon
                marker.append(createSketchesPoi(61.3,7.2));//lat,lon
                marker.append(createSketchesPoi(61.3,7.24));//lat,lon
                marker.append(createSketchesPoi(61.3,7.4));//lat,lon
                marker.append(createSketchesPoi(61.3,7.0));//lat,lon
                marker.append(createSketchesPoi(61.2,7.2));//lat,lon
                marker.append(createSketchesPoi(61.4,7.2));//lat,lon
                marker.append(createSketchesPoi(61.28,7.2));//lat,lon
                marker.append(createSketchesPoi(61.32,7.2));//lat,lon
                marker.append(createSketchesPoi(61.24,7.12));//lat,lon
                marker.append(createSketchesPoi(61.24,7.28));//lat,lon
                marker.append(createSketchesPoi(61.36,7.12));//lat,lon
                marker.append(createSketchesPoi(61.36,7.28));//lat,lon

                //add the settings, such as icon image size, to the markers;

                //SKETCHES
                let sketchlist = map.markerCollection.getExtendedList(MarkerList.Type.Point);
                sketchlist.append(marker, markerRenderSettings);

                console.log("marker sketchlist len:" + sketchlist.length + " icon coords:" + sketchlist.get(0).length);
                console.log("marker len:"+marker.length+" renderset:"+markerRenderSettings);

                //the following block is used only to autocenter on the group of landmarks;
                {
                    map.centerOnGeographicArea(routingWaypoints.boundingBox)
                }
            }
        }
        Button {
                //anchors.left: parent.left
                //anchors.top: parent.top
                text: "Clear sketches"
                onClicked: {
                    //show how to clear sketches-type marker icons from the map;
                    //clear the list of points used for centering on the bounding box
                    //containing all points/landmarks/waypoints/markers/icons;
                    routingWaypoints.clear();
                    //also clear the markerlist used for rendering the points on the map;
                    //the same set of coordinates is in each of these lists, so both must
                    //be cleared;
                    let sketchlist = map.markerCollection.getExtendedList(MarkerList.Type.Point);
                    sketchlist.clear();
                }
            }
        }
    }
}
//! [MapView code]
