/*
 * 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.Components 1.3
import Ubuntu.Components.Popups 1.3
import QtQuick.LocalStorage 2.0
import "js/db.js" as UnavDB
import "components"

Page {
    id: settingsPage

    header: UNavHeader {
        title: i18n.tr("Settings")
        flickable: flickable
        
        // #FIXME: This back button is only here to allow the user to press Escape keyboard key to go back.
        // This feature will be implemented upstream by the SDK devs when they add keyboard shortcuts to pages,
        // at which point this back button can be removed.
        leadingActionBar.actions: Action {
            iconName: "back"
            text: i18n.tr("Back")
            shortcut: "Escape"
            onTriggered: {
                mainPageStack.pop()
            }
        }
        
        trailingActionBar.actions: Action {
            id: actionInfo
            iconName: "info"
            text: i18n.tr("About")
            onTriggered: mainPageStack.push(Qt.resolvedUrl("AboutPage.qml"))
        }
    }

    signal settingsChanged()

    ListModel {
        id: navigationModeModel
        Component.onCompleted: initialize()
        function initialize() {
            navigationModeModel.append({ "mode": i18n.tr("Car"), "index": 0 })
            navigationModeModel.append({ "mode": i18n.tr("Walking"), "index": 1 })
            navigationModeModel.append({ "mode": i18n.tr("Bicycle"), "index": 2 })

            modeList.subText.text = navigationModeModel.get(navApp.settings.routingMode).mode
        }
    }

    ListModel {
        id: soundModel
        Component.onCompleted: initialize()
        function initialize() {
            soundModel.append({ "sound": i18n.tr("A Voice"), "index": 0 })
            soundModel.append({ "sound": i18n.tr("A Notification"), "index": 1 })
            soundModel.append({ "sound": i18n.tr("None"), "index": 2 })

            soundList.subText.text = soundModel.get(navApp.settings.soundIndications).sound
        }
    }

    ListModel {
        id: unitModel
        Component.onCompleted: initialize()
        function initialize() {
            unitModel.append({ "unit": i18n.tr("Kilometres"), "index": 0 })
            unitModel.append({ "unit": i18n.tr("Miles"), "index": 1 })

            unitList.subText.text = unitModel.get(navApp.settings.unit).unit
        }
    }

    Flickable {
        id: flickable
        anchors.fill: parent
        contentHeight: settingsColumn.height + units.gu(5)

        Column {
            id: settingsColumn

            anchors {
                top: parent.top
                left: parent.left
                right: parent.right
            }

            ListItemHeader {
                 id: navigationListHeader
                 title: i18n.tr("Navigation")
            }

            ExpandableListItem {
                id: modeList

                listViewHeight: units.gu(12+1)
                titleText.text: i18n.tr("Navigation Mode")

                model: navigationModeModel

                delegate: ListItem {
                    divider.visible: false
                    height: navigationListItemLayout.height
                    ListItemLayout {
                        id: navigationListItemLayout
                        title.text: model.mode
                        title.color: "#5D5D5D"
                        padding { top: units.gu(1); bottom: units.gu(1) }
                        Icon {
                            SlotsLayout.position: SlotsLayout.Trailing
                            width: units.gu(2)
                            name: "tick"
                            visible: navApp.settings.routingMode === model.index
                        }
                    }

                    onClicked: {
                        navApp.settings.routingMode = model.index
                        mainPageStack.executeJavaScript("if (nav.get_route_status() != 'no' && !nav.get_route_status().startsWith('simulate')){nav.set_route_status('waiting4signal')}; settings.set_routing_mode(" + model.index +");")
                        modeList.subText.text = navigationModeModel.get(navApp.settings.routingMode).mode
                        modeList.toggleExpansion()
                    }
                }
            }

            ListItem {
                visible: navApp.settings.routingMode === 0
                height: tollsLayout.height + divider.height
                ListItemLayout {
                    id: tollsLayout
                    title.text: i18n.tr("Avoid Tolls")
                    Switch {
                        id: tollsSwitch
                        checked: navApp.settings.avoidTolls
                        onClicked: {
                            navApp.settings.avoidTolls = checked;
                            mainPageStack.executeJavaScript("if (nav.get_route_status() != 'no'){nav.set_route_status('waiting4signal')}; settings.set_avoid_tolls(" + checked.toString() + ");")
                        }
                        SlotsLayout.position: SlotsLayout.Last
                    }
                }
            }

            ListItem {
                visible: navApp.settings.routingMode === 0
                height: speedCameraLayout.height + divider.height
                ListItemLayout {
                    id: speedCameraLayout
                    title.text: i18n.tr("Speed Camera Alerts")
                    Switch {
                        id: radarsSwitch
                        checked: navApp.settings.alertRadars
                        onClicked: {
                            navApp.settings.alertRadars = checked;
                            mainPageStack.executeJavaScript("if (nav.get_route_status() != 'no'){nav.set_route_status('waiting4signal')}; settings.set_alert_radars(" + checked.toString() + ");");
                            if (navApp.settings.legalRadarShow) {
                                navApp.settings.legalRadarShow = false;
                                PopupUtils.open(confirmEnableRadar);
                            }
                        }
                        SlotsLayout.position: SlotsLayout.Last
                    }
                }
            }

            ExpandableListItem {
                id: soundList

                listViewHeight: units.gu(12+1)
                titleText.text: i18n.tr("Guidance")

                model: soundModel

                delegate: ListItem {
                    divider.visible: false
                    height: soundListItemLayout.height
                    ListItemLayout {
                        id: soundListItemLayout
                        title.text: model.sound
                        title.color: "#5D5D5D"
                        padding { top: units.gu(1); bottom: units.gu(1) }
                        Icon {
                            SlotsLayout.position: SlotsLayout.Trailing
                            width: units.gu(2)
                            name: "tick"
                            visible: navApp.settings.soundIndications === model.index
                        }
                    }

                    onClicked: {
                        navApp.settings.soundIndications = model.index
                        mainPageStack.executeJavaScript("settings.set_sound(" + model.index + ");")
                        soundList.subText.text = soundModel.get(navApp.settings.soundIndications).sound
                        soundList.toggleExpansion()
                    }
                }
            }

           ListItemHeader {
                id: mapListHeader
                title: i18n.tr("Map")
            }

           ExpandableListItem {
               id: unitList

               listViewHeight: units.gu(8+1)
               titleText.text: i18n.tr("Units")

               model: unitModel

               delegate: ListItem {
                   divider.visible: false
                   height: unitListItemLayout.height
                   ListItemLayout {
                       id: unitListItemLayout
                       title.text: model.unit
                       title.color: "#5D5D5D"
                       padding { top: units.gu(1); bottom: units.gu(1) }
                       Icon {
                           SlotsLayout.position: SlotsLayout.Trailing
                           width: units.gu(2)
                           name: "tick"
                           visible: navApp.settings.unit === model.index
                       }
                   }

                   onClicked: {
                       navApp.settings.unit = model.index
                       mainPageStack.executeJavaScript("settings.set_unit(\'" + ( model.index === 0 ? "km" : "mi" ) +"\');")
                       mainPageStack.executeJavaScript("ui.set_scale_unit(\'" + ( navApp.settings.unit === 0 ? "km" : "mi" ) +"\');")
                       unitList.subText.text = unitModel.get(navApp.settings.unit).unit
                       unitList.toggleExpansion()
                   }
               }
           }

           ListItem {
               height: hidePageHeaderLayout.height + divider.height
               ListItemLayout {
                   id: hidePageHeaderLayout
                   title.text: i18n.tr("Show header in map view")
                   Switch {
                       id: hidePageHeaderSwitch
                       checked: navApp.settings.headerVisible
                       onClicked: navApp.settings.headerVisible = checked
                       SlotsLayout.position: SlotsLayout.Last
                   }
               }
           }

            ListItemHeader {
                id: privacyListHeader
                title: i18n.tr("History")
            }

            ListItem {
                height: storeSearchLayout.height + divider.height
                ListItemLayout {
                    id: storeSearchLayout
                    title.text: i18n.tr("Store new searches")
                    Switch {
                        id: saveHistorySwitch
                        checked: navApp.settings.saveHistory
                        onClicked: navApp.settings.saveHistory = checked
                        SlotsLayout.position: SlotsLayout.Last
                    }
                }
            }

            ListItem {
                ListItemLayout {
                    title.text: i18n.tr("Clear History")
                }
                onClicked: PopupUtils.open(confirmEraseHistory)
            }
        }

        Component {
            id: confirmEraseHistory
            Dialog {
                id: dialogueErase
                title: i18n.tr("Clear History")
                text: i18n.tr("You'll delete the current history")

                Button {
                    text: i18n.tr("Delete")
                    color: UbuntuColors.red
                    onClicked: {
                        UnavDB.dropHistoryTables();
                        PopupUtils.close(dialogueErase);
                    }
                }

                Button {
                     text: i18n.tr("Cancel")
                     onClicked: PopupUtils.close(dialogueErase)
                }
            }
        }

        Component {
            id: confirmEnableRadar
            Dialog {
                id: dialogueRadars
                title: i18n.tr("Speed Camera alerts and the law")
                text: i18n.tr("uNav is only reading the OpenStreetMap database.\nuNav will show a max speed notification and a Speed Camera marker (marker hidden for French users because of law).\n\nIn a few countries Speed Camera alerts are illegal, then enable this option only if it's legal in the country.")
                Label {
                    width: parent.width
                    color: UbuntuColors.slate
                    wrapMode: Text.WordWrap
                    horizontalAlignment: Text.AlignHCenter
                    text: i18n.tr("Read more about it %1.").arg("<a href=\"http://goo.gl/ulXvG8\">here</a>")
                    onLinkActivated: Qt.openUrlExternally(link)
                }
                Button {
                    text: i18n.tr("OK")
                    color: UbuntuColors.red
                    onClicked: PopupUtils.close(dialogueRadars);
                }
            }
        }
    }
}
