/****************************************************************************
**
** Copyright (C) 2019-2022 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
** Copyright (C) 2019-2022 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."
****************************************************************************/

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
//! [AddressSearchService plumbing]
import QtQuick.Window 2.12
import GeneralMagic 2.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Address Search Example")
    Component.onCompleted: {
        //! [Set token safely]
        ServicesManager.settings.token = __my_secret_token;
        //! [Set token safely]
        ServicesManager.settings.allowInternetConnection = true; // enable connection to online services

        ServicesManager.contentUpdater(ContentItem.Type.RoadMap).autoApplyWhenReady = true;
        ServicesManager.contentUpdater(ContentItem.Type.RoadMap).update();
    }
    //! [AddressSearchService plumbing]

    //! [AddressSearchService timer]
    Timer {
        id: searchTimer
        interval: 500
        onTriggered: {
            addressSearch.searchNow();
        }
    }
    //! [AddressSearchService timer]

    //! [AddressSearchService model]
    AddressSearchService {
        id: addressSearch
        property LandmarkList levels: LandmarkList {
            Landmark {
                name: "All Countries"
            }
        }
        detailToSearch: nextAddressDetailLevel(parentLandmark)[0]
        filter: filterTextField.text
        maximumMatches: detailToSearch == AddressSearchService.Country ? 150 : 50;
        automaticLevelSkip: true

        function searchNow() {
            searchTimer.stop();
            search();
        }
    }
    //! [AddressSearchService model]

    MapView {
        id: mapView
        anchors.fill: parent

        Rectangle {
            anchors.fill: parent
            color: Qt.rgba(0,0,0,0.5)
            anchors.margins: 30
            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 15
                //! [AddressSearchService input]
                TextField {
                    id: filterTextField
                    Layout.fillWidth: true
                    placeholderText: {
                        switch(addressSearch.detailToSearch) {
                        case 0:
                            return ""
                        case 1:
                            return "Country"
                        case 2:
                            return "State"
                        case 3:
                            return "County"
                        case 4:
                            return "District"
                        case 5:
                            return "City"
                        case 6:
                            return "Settlement"
                        case 7:
                            return "Post Code"
                        case 8:
                            return "Street"
                        case 9:
                            return "Section"
                        case 10:
                            return "Lane"
                        case 11:
                            return "Alley"
                        case 12:
                            return "Number"
                        case 13:
                            return "Crossing"
                        }
                    }
                    enabled: addressSearch.detailToSearch != 0
                    onTextEdited: searchTimer.restart()
                    onEditingFinished: addressSearch.searchNow()
                }
                //! [AddressSearchService input]
                RowLayout {
                    Layout.fillHeight: true
                    Layout.fillWidth: true
                    //! [AddressSearchService previousLevels]
                    ListView {
                        Layout.fillHeight: true
                        Layout.fillWidth: true
                        clip: true
                        model: addressSearch.levels.children
                        delegate: Text {
                            text: (index == 0 ? "" : "-> ") + name
                            color:"white"
                            wrapMode: Text.WrapAnywhere
                            anchors.left: parent.left
                            anchors.leftMargin: index * 10
                            MouseArea {
                                anchors.fill: parent
                                onClicked: {
                                    addressSearch.parentLandmark = index === 0 ? null : addressSearch.levels.children[index];
                                    filterTextField.text = "";
                                    addressSearch.search();
                                    if (index > 0) {
                                        mapView.centerOnCoordinates(addressSearch.parentLandmark.coordinates, mapView.maxZoomLevel - mapView.maxZoomLevel / (Math.pow(index, 2) + 1));
                                    }
                                    if (index + 1 < addressSearch.levels.size())
                                        addressSearch.levels.remove(index + 1, addressSearch.levels.size() - index - 1);
                                }
                            }
                        }
                    }
                    //! [AddressSearchService previousLevels]

                    //! [AddressSearchService nextLevel]
                    ListView {
                        Layout.fillHeight: true
                        Layout.fillWidth: true
                        model: addressSearch
                        delegate: Text {
                            text: landmark.name
                            color:"white"
                            wrapMode: Text.WrapAnywhere
                            MouseArea {
                                anchors.fill: parent
                                onClicked: {
                                    addressSearch.parentLandmark = addressSearch.get(index);
                                    addressSearch.levels.append(addressSearch.parentLandmark);
                                    filterTextField.text = "";
                                    mapView.hideHighlights();
                                    if (addressSearch.parentLandmark.geographicArea.valid) {
                                        mapView.centerOnGeographicArea(addressSearch.parentLandmark.geographicArea);
                                        mapView.highlightLandmark(addressSearch.parentLandmark, MapView.HighlightOption.ShowContour, Qt.rgba(1, 0, 0, 0.7), Qt.rgba(0, 1, 0, 0.7));
                                    } else {
                                        mapView.centerOnCoordinates(addressSearch.parentLandmark.coordinates, mapView.maxZoomLevel - mapView.maxZoomLevel / (Math.pow(addressSearch.levels.size() - 1 , 2) + 1));
                                    }
                                    addressSearch.search();
                                }
                            }
                        }
                    }
                    //! [AddressSearchService nextLevel]
                }
            }
        }
    }
}
